EF4 Code First - 如何正确映射跨多个表分割实体 [英] EF4 Code First - How to properly map Splitting an Entity Across Multiple Tables

查看:190
本文介绍了EF4 Code First - 如何正确映射跨多个表分割实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF4 CTP5来尝试保留两个表之间分裂的POCO对象,该链接是ContactID。当我保存联系人时,我希望保存在一个表(联系人)中的核心联系人信息,以及保存在另一个表(UserToContacts)中的拥有该联系人的用户的链接。我有下面定义的自定义映射,但是当我保存更改时,我收到以下错误:

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:

跨多个实体或关联共享的值生成在多个位置。检查该映射不会将EntityKey拆分为多个存储生成的列。

任何想法将不胜感激!

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


推荐答案

这是一个错误,EF CTP5发布后,团队将其修正为代码库。实体拆分只应导致在其中一个表上使用身份,但是CTP5会为所有表配置它(如果您查看表,您会看到 ContactID 被配置为两个身份列)。

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

这意味着您有责任在创建新的Contact对象时提供有效的PK 。

Which means you are responsible to provide valid PKs when creating a new Contact object.

这篇关于EF4 Code First - 如何正确映射跨多个表分割实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆