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

帅比萌擦擦* 提交于 2019-12-30 09:39:15

问题


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");
        });
    }

回答1:


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.




回答2:


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");
    });
}


来源:https://stackoverflow.com/questions/5021742/ef4-code-first-how-to-properly-map-splitting-an-entity-across-multiple-tables

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