EF4 Code First - How to properly map Splitting an Entity Across Multiple Tables
I am using EF4 CTP5 to try to persist a POCO object that is split among two tables, the link being the ContactID. When开发者_运维问答 i save a contact, i want the core contact information saved in one table (Contacts), and the link to the user who owns the contact saved in another (UserToContacts). I have the custom mapping defined below, but when I SaveChanges, i get the following error:
A value shared across entities or associations is generated in more than one location. Check that mapping does not split an EntityKey to multiple store-generated columns.
Any ideas would be greatly appreciated!
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
/// Perform Custom Mapping
modelBuilder.Entity<Contact>()
.Map(mc =>
{
mc.Properties(p => new
{
p.ContactID,
p.FirstName,
p.MiddleName,
p.LastName
});
mc.ToTable("Contacts");
})
.Map(mc =>
{
mc.Properties(p => new
{
p.ContactID,
p.UserID
});
mc.ToTable("UserToContacts");
});
}
This is a bug that EF team have fixed it in their code base after CTP5 was released. Entity splitting should only result in identity being used on one of the tables but CTP5 configures it for all tables (if you look into your tables you'll see that ContactID
is configured as an identity column in both).
The workaround for now is to not using identity with table splitting at all:
public class Contact
{
[DatabaseGenerated(DatabaseGenerationOption.None)]
public int ContactID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public int UserID { get; set; }
}
Which means you are responsible to provide valid PKs when creating a new Contact object.
Just don't specify the ID, it will be added automatically
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
/// Perform Custom Mapping
modelBuilder.Entity<Contact>()
.Map(mc =>
{
mc.Properties(p => new
{
p.FirstName,
p.MiddleName,
p.LastName
});
mc.ToTable("Contacts");
})
.Map(mc =>
{
mc.Properties(p => new
{
p.UserID
});
mc.ToTable("UserToContacts");
});
}
精彩评论