The following code was working with EFCore 2.0.
Since the 2.1 update, I get a blocking bug:
The child/dependent side could not be determined for the one-to-one relationship
between 'Entity2.Main' and 'Entity1.Metadata'.
To identify the child/dependent side of the relationship, configure the foreign key property.
If these navigations should not be part of the same relationship configure them without specifying
the inverse. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.
The tables are something like (they share the same id, but on different tables):
Table_Entity1:
- Id
- Name
- Description
Table_Entity2:
- Id
- Flag1
- Flag2
Entities are like:
public class Entity1
{
public long Id {get;set;}
public string Name {get;set;}
public string Description {get;set;}
public Entity2 Metadata {get;set;}
}
public class Entity2
{
public long Id {get;set;}
public bool Flag1 {get;set;}
public bool Flag2 {get;set;}
public Entity1 Main {get;set;}
}
They are declared as follow:
builder.Entity<Entity1>(b =>
{
b.HasKey(e => e.Id);
b.Property(e => e.Id).ValueGeneratedNever();
b.HasOne<Entity2>(e => e.Metadata)
.WithOne(e => e.Main)
.HasForeignKey<Entity2>(e => e.Id)
.HasPrincipalKey<Entity1>(e=>e.Id);
b.ToTable("Table_Entity1");
});
builder.Entity<Entity2>(b =>
{
b.HasKey(e => e.Id);
b.ToTable("Table_Entity2");
});
How can I solve this? I have tried all HasOne, WithOne, HasForeignKey combinations, nothing seem to work...
By looking at your models, it seems to me Entity 1 owns Entity 2. Have you followed what's suggested in the Microsoft Document Owned Entity Types section: https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities?
You can try to change the models to:
public class Entity2
{
public bool Flag1 { get; set; }
public bool Flag2 { get; set; }
}
public class Entity1
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Entity2 Metadata { get; set; }
}
Then on the configurations:
builder.Entity<Entity1>(b =>
{
b.HasKey(e1 => e1.Id);
b.OwnsOne(e1 => e1.Metadata, md => {
// I think the example on the Microsoft Doc is wrong but need to verify.
// I opened an issue here:
// https://github.com/aspnet/EntityFramework.Docs/issues/772
md.ToTable("Table_Entity2");
});
b.ToTable("Table_Entity1");
});
Disclaim: I wrote anything by hand hence they're not tested.
I have solved it by adding OwnsOne:
builder.Entity<Entity1>(b =>
{
b.HasKey(e => e.Id);
b.Property(e => e.Id).ValueGeneratedNever();
b.OwnsOne<Entity2>(e => e.Metadata);
b.HasOne<Entity2>(e => e.Metadata)
.WithOne(e => e.Main)
.HasForeignKey<Entity2>(e => e.Id);
b.ToTable("Table_Entity1");
});
builder.Entity<Entity2>(b =>
{
b.HasKey(e => e.Id);
b.ToTable("Table_Entity2");
});
Related
I have this situation where I have been unable to correctly fetch my dependent class using an Include in EF Core 3.1 when fetching the principal. This situation might be a little different to MS's docs as in the dependent class the PK and FK are on the same field, FileDefinitionId
Despite all of the code below, fileDefinition.FileImportDefinition is null.
Is there something I have missed? I've been following Microsoft's docs on this
fileDefinition = context.FileDefinitions
.AsNoTracking()
.Include(x => x.FileImportDefinition)
.FirstOrDefault(p => p.FileDefinitionId == fileDefinitionId);
Principal
public partial class FileDefinition
{
public long FileDefinitionId { get; set; }
public virtual FileImportDefinition FileImportDefinition { get; set; }
}
Dependent
public partial class FileImportDefinition
{
public long FileDefinitionId { get; set; }
public virtual FileDefinition FileDefinition { get; set; }
}
OnModelBuilding - FileDefinition (principal)
entity.HasOne(d => d.FileImportDefinition)
.WithOne(p => p.FileDefinition)
.IsRequired(false)
.HasForeignKey<FileImportDefinition>(d => d.FileDefinitionId)
.HasConstraintName("FK_FileImportDefinitions_FileDefinitions")
.OnDelete(DeleteBehavior.ClientSetNull);
I started working on an ongoing project and it has a many-to-many relationship in the database and in some parts of the code too, but I realized that even the relationship being many-to-many in the model there is always only one line linking the two entities (confirmed with the author). This is what I mean: The two entities are task and task list and a task only belongs to a task list. Models below:
public class ProjectTask
{
public long Id { get; set; }
// other non related properties
}
public class ProjectTaskList
{
public long Id { get; set; }
public DateTime? DateEnd { get; set; }
// other non related properties
}
// link between task list and task
public class ProjectTaskListTask
{
public long ProjectTaskId { get; set; }
public ProjectTask ProjectTask { get; set; }
public long ProjectTaskListId { get; set; }
public ProjectTaskList ProjectTaskList { get; set; }
public int Order { get; set; }
}
And its configuration in the OnModelCreating method of the context class:
modelBuilder.Entity<ProjectTaskListTask>()
.HasKey(a => new { a.ProjectTaskId, a.ProjectTaskListId });
modelBuilder.Entity<ProjectTaskListTask>()
.HasOne(u => u.ProjectTaskList)
.WithMany(u => u.Tasks)
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
My problem is: In some parts of my code I need to know the Task List of a task, I need to use it in Where queries to do some validations, like : Tasks.Where(p => p.TaskList.DateEnd == null).
How can I add a Not Mapped property to the ProjectTask entity so I could do that? I'm using Entity Framework Core 2.
Thanks for any help
Without changing the underlying data structure, could you query ProjectTaskListTask? Something along the lines...?
ProjectTaskListTask
.Include(p => p.ProjectTaskList)
.Include(p => p.ProjectTask)
.Where(p => p.ProjectTaskList.DateEnd == null)
.Select(p => p.ProjectTask);
User-Friend relationship
I find an answer
Entity Framework Core: many-to-many relationship with same entity
and try like this.
Entitys:
public class User
{
public int UserId { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
}
public class Friend
{
public int MainUserId { get; set; }
public User ManUser { get; set; }
public int FriendUserId { get; set; }
public User FriendUser { get; set; }
}
The fluent API:
modelBuilder.Entity<Friend>()
.HasKey(f => new { f.MainUserId, f.FriendUserId });
modelBuilder.Entity<Friend>()
.HasOne(f => f.ManUser)
.WithMany(mu => mu.Friends)
.HasForeignKey(f => f.MainUserId);
modelBuilder.Entity<Friend>()
.HasOne(f => f.FriendUser)
.WithMany(mu => mu.Friends)
.HasForeignKey(f => f.FriendUserId);
When I Add-Migration, the error message is
Cannot create a relationship between 'User.Friends' and 'Friend.FriendUser', because there already is a relationship between 'User.Friends' and 'Friend.ManUser'.
Navigation properties can only participate in a single relationship.
What should I do? Or I should create an Entity FriendEntity:User?
The problem is that you can't have one collection to support both one-to-many associations. Friend has two foreign keys that both need an inverse end in the entity they refer to. So add another collection as inverse end of MainUser:
public class User
{
public int UserId { get; set; }
public virtual ICollection<Friend> MainUserFriends { get; set; }
public virtual ICollection<Friend> Friends { get; set; }
}
And the mapping:
modelBuilder.Entity<Friend>()
.HasKey(f => new { f.MainUserId, f.FriendUserId });
modelBuilder.Entity<Friend>()
.HasOne(f => f.MainUser)
.WithMany(mu => mu.MainUserFriends)
.HasForeignKey(f => f.MainUserId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Friend>()
.HasOne(f => f.FriendUser)
.WithMany(mu => mu.Friends)
.HasForeignKey(f => f.FriendUserId);
One (or both) of the relationships should be without cascading delete to prevent multiple cascade paths.
It's not mandatory the second collection. You only need to left de .WithMany() empty like this:
modelBuilder.Entity<Friend>()
.HasOne(f => f.MainUser)
.WithMany()
.HasForeignKey(f => f.MainUserId);
modelBuilder.Entity<Friend>()
.HasOne(f => f.FriendUser)
.WithMany()
.HasForeignKey(f => f.FriendUserId);
look at this : https://github.com/aspnet/EntityFramework/issues/6052
I am trying to split a legacy user table into two entities using a one to one mapping but keep getting migration errors stating that my database is out of sync, even though everything (i think is mapped) and i am trying to make a one-to-one relationship.
This is an existing database (although i am using code first as migrations will become important down the line) but i have not added any changes to the database (although i am unsure what exactly the one-to-one table split expects), i keep getting this:
The model backing the 'Context' context has changed since the database was created. Consider using Code First Migrations to update the database
I can update the database (either manually or via Migrations) but have no idea what is actually out of sync as no new fields have been added and the names match up.
BaseEntity:
public abstract class BaseEntity<T>
{
[Key]
public T Id { get; set; }
public DateTime CreatedOn { get; set; }
}
Membership Model:
public class Membership : BaseEntity<Guid>
{
public string UserName { get; set; }
public bool Approved { get; set; }
public bool Locked { get; set; }
public Profile Profile { get; set; }
}
Profile Model:
public class Profile : BaseEntity<Guid>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Extension { get; set; }
public Membership Membership { get; set; }
}
Membership Mapping (this has the 1 to 1 Definition):
public class MembershipMap : EntityTypeConfiguration<Membership>
{
public MembershipMap()
{
//Primary Key
this.HasKey(t => t.Id);
//**Relationship Mappings
this.HasRequired(m => m.Profile)
.WithRequiredPrincipal(p => p.Membership);
//Properties & Column mapping
this.Property(m => m.Id)
.HasColumnName("PKID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(m => m.UserName)
.HasColumnName("Username")
.HasMaxLength(255);
this.Property(m => m.Approved)
.HasColumnName("IsApproved");
this.Property(m => m.Locked)
.HasColumnName("IsLocked");
this.Property(m => m.CreatedOn)
.HasColumnName("CreationDate");
this.ToTable("AppUser");
}
}
Profile Mapping:
public class ProfileMap : EntityTypeConfiguration<Profile>
{
public ProfileMap()
{
//Primary Key
this.HasKey(t => t.Id);
//Properties & Column mapping
this.Property(m => m.Id)
.HasColumnName("PKID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(m => m.FirstName)
.HasColumnName("FirstName");
this.Property(m => m.LastName)
.HasColumnName("LastName");
this.Property(m => m.Email)
.HasColumnName("Email");
this.Property(m => m.Telephone)
.HasColumnName("Telephone");
this.Property(m => m.Extension)
.HasColumnName("Extension");
this.ToTable("AppUser");
}
}
Database Table
I know that not all fields are mapped, but i do not need them at this stage, surely that wouldn't be the issue would it?
Issue was not Code First Mappings but caused by me switching databases and some rouge migrations coming into play.
To reset migrations you can see the answer here from a follow up question:
Resetting Context for Entity Framework 5 so it thinks its working with a initialised Database - Code First
Kudos to EvilBHonda
UPDATE: After a bit more research it seems a number of my many-to-many mappings aren't working. Hmmm...
I'm upgrading a data access project from EF 4.1 CTP4 to EF 4.1 RC and I'm having trouble with the new EntityTypeConfiguration<T> setup.
Specifically I'm having an issue with a Many-to-Many relationship. I'm getting a Sequence contains no elements exception when I'm trying to get the .First() item.
The particular exception isn't really that interesting. All it's saying is that there are no items BUT I know there should be items in the collection - so there must be an issue with my new mappings.
Here's the code I have so far:
Product Model
public class Product : DbTable
{
//Blah
public virtual ICollection<Tag> Categories { get; set; }
public Product()
{
//Blah
Categories = new List<Tag>();
}
}
BaseConfiguration
public class BaseConfiguration<T> : EntityTypeConfiguration<T> where T : DbTable
{
public BaseConfiguration()
{
this.HasKey(x => x.Id);
this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(x => x.UpdatedOn);
this.Property(x => x.CreatedOn);
}
}
ProductConfiguration
public class ProductConfiguration : BaseConfiguration<Product>
{
public ProductConfiguration()
{
this.ToTable("Product");
//Blah
this.HasMany(x => x.Categories)
.WithMany()
.Map(m =>
{
m.MapLeftKey("Tag_Id");
m.MapRightKey("Product_Id");
m.ToTable("ProductCategory");
});
}
}
Previous CTP4 Mapping the worked!
this.HasMany(x => x.Categories)
.WithMany()
.Map("ProductCategory", (p, c) => new { Product_Id = p.Id, Tag_Id = c.Id });
Can anyone see anything that needs fixing? Let me know if you want me to provide more code.
EDIT: More Code
DbTable
public class DbTable : IDbTable
{
public int Id { get; set; }
public DateTime UpdatedOn { get; set; }
public DateTime CreatedOn { get; set; }
}
Tag
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public bool Visible { get; set; }
public virtual TagType TagType { get; set; }
}
TagConfiguration
public class TagConfiguration : EntityTypeConfiguration<Tag>
{
public TagConfiguration()
{
this.ToTable("Tags");
this.HasKey(x => x.Id);
this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnName("tag_id");
this.Property(x => x.Name).HasMaxLength(300).HasColumnName("tag_name");
this.Property(x => x.Slug).HasMaxLength(500).HasColumnName("tag_slug");
this.Property(x => x.Visible).HasColumnName("tag_visible");
this.HasRequired(x => x.TagType).WithMany(tt => tt.Tags).Map(m => m.MapKey("tagtype_id"));
}
}
Yes, this is a legacy database with naming conventions up to boohai.
I know the Tag class must be wired up correctly because Product has another property Specialization which is also mapped to Tag and it loads correctly. But do note that it's mapped in a one-to-many manner. So it seems to be the many-to-many with Tag.
I'll start checking out if any many-to-many associations are working.
You need to specify both navigation properties to do many to many mapping.
Try adding the lambda in the WithMany property pointing back to the products:
this.HasMany(x => x.Categories)
.WithMany(category=>category.Products)
.Map(m =>
{
m.MapLeftKey(t => t.TagId, "Tag_Id");
m.MapRightKey(t => t.ProductId, "Product_Id");
m.ToTable("ProductCategory");
});
(crossing fingers...)
I haven't used the Code-First approach yet, but when working with POCOs I had to enable Lazy-Loading, to make Navigation Properties work. This is of course by design, but I don't know if you have to explicitly enable this behavior for Code-First.