Reputation: 521
I'm teaching myself Entity framework core. Actually I'm relatively new to the whole .net world.
I've classes like below (apologies for the pseudo-code, actual code is too long to paste here).
Account
{
User UserInfo {get;set;}
}
User
{
string Email {get;set;}
}
Admin:Account
{
// some properties
}
I'm trying to generate db tables using the EF code first pattern. With the above classes, I've a seed routine that looks like below :
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>().HasData(
new Admin
{
UserInfo = new User {Email = "[email protected]"}
});
}
With the above, when I try to create an initial migration, I get the below error:
The seed entity for entity type 'Account' cannot be added because the value provided is of a derived type 'Admin'. Add the derived seed entities to the corresponding entity type.
So, I changed the code like below (replacing Account with Admin):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Admin>().HasData(
new Admin
{
UserInfo = new User {Email = "[email protected]"}
});
}
And now I'm getting this error (not sure where UserInfoEmail
is coming from) :
The seed entity for entity type 'Admin' cannot be added because it has the navigation 'UserInfo' set. To seed relationships you need to add the related entity seed to 'User' and specify the foreign key values {'UserInfoEmail'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.
I'm at a loss understanding this whole concept of handling relationships when using code first pattern. Can someone please help me understand what does the above errors mean, and how to handle relationships (esp composition & inheritence) when using EF code first pattern.
Upvotes: 1
Views: 858
Reputation: 4375
Second attempt was close, but you did one mistake:
modelBuilder.Entity<Admin>().HasData(
new Admin
{
UserInfo = new User {Email = "[email protected]"}
});
Look, here you set UserInfo
to new User
. Your error means that you cannot add User
entity while trying to add Admin
entity. Instead add User
first and reference it from Admin
entity later (looks like Email
is your primary key in User
entity):
modelBuilder.Entity<User>().HasData(
new User
{
Email = "[email protected]"
});
modelBuilder.Entity<Admin>().HasData(
new Admin
{
UserInfoId = "[email protected]"
});
If you don't have UserInfoId
in Account
class, just add it:
class Account
{
User UserInfo { get; set; }
string UserInfoId { get; set; }
}
Upvotes: 1