EF4 Code First - How to properly map Splitting an Entity Across Multiple Tables

被刻印的时光 ゝ 提交于 2019-12-01 05:55:46

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");
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!