加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – EF多重关系

发布时间:2020-12-15 21:41:25 所属栏目:百科 来源:网络整理
导读:使用实体框架5 所以我有一个客户.客户可以有多个地址,但至少有一个.其中一个地址也将被设置为主要地址(必需).我尝试了各种映射,但到目前为止,我在构建或种子数据库时遇到错误. 顾客: public class Customer{ public int CustomerId { get; set;} public Str
使用实体框架5

所以我有一个客户.客户可以有多个地址,但至少有一个.其中一个地址也将被设置为主要地址(必需).我尝试了各种映射,但到目前为止,我在构建或种子数据库时遇到错误.

顾客:

public class Customer
{
    public int CustomerId { get; set;}
    public String CustomerName { get; set; }
    public int PrimaryAddressId { get; set; }
    public virtual CustomerAddress PrimaryAddress { get; set; }
    public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; }    
}

地址:

public class CustomerAddress : Address
{
    public int CustomerAddressId { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

这部分映射工作正常.它位于CustomerAddress上.

this.HasRequired(c => c.Customer)
            .WithMany(d => d.CustomerAddresses)
            .HasForeignKey(c => c.CustomerId);

但是如何指定在Customer中设置PrimaryAddress的正确映射?或者这是错误的方法?

谢谢

编辑 – 使用Arnolds和LueTM的答案:

此代码现在正在运行.

顾客:

public class Customer
{
    public int CustomerId { get; set;}
    public String CustomerName { get; set; }
    // public int PrimaryAddressId { get; set; } created in mapping
    public virtual CustomerAddress PrimaryAddress { get; set; }
    public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; }    
}

地址:

public class CustomerAddress : Address
{
    public int CustomerAddressId { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
}

客户映射:

modelBuilder.Entity<Customer>
            .HasOptional(c => c.PrimaryAddress)
            .WithOptionalDependent().Map(m => m.MapKey("PrimaryAddressId"));

        modelBuilder.Entity<Customer>
            .HasMany(c => c.CustomerAddresses)
            .WithRequired(c => c.Customer)
            .HasForeignKey(c => c.CustomerId)
            .WillCascadeOnDelete(false);

我使用存储库来确保首先创建一个新地址,保存,然后再设置为主地址并再次保存.存储库确保主要是“必需的”.

解决方法

既然你没有显示异常,我必须假设你遇到了鸡蛋问题.

如果将PrimaryAddress设置为必需属性,则EF必须具有现有地址Id才能建立外键(在Customer中设置PrimaryAddressId).但是,由于地址要求客户,您无法在其客户之前存储地址.如果您尝试一次保存地址和客户,EF无法确定插入的正确顺序,因为它需要插入具有另一个对象的生成Id的两个对象.

因此,地址或客户必须具有可选的外键.

我会使Customer.PrimaryAddressId可选:

modelBuilder.Entity<Customer>().HasOptional(c => c.PrimaryAddress)
    .WithOptionalDependent();

现在,您可以在separeate事务中存储地址并为客户分配主要地址.但是,您需要业务逻辑来确保客户始终拥有主要地址.

如果要在一个事务中保存cutomer和地址,可以采用一种方法将IsPrimary属性(bool)添加到CustomerAddress,并确保始终只有一个地址为true.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读