Code First 重复外键

原因:在一个表中,我有如下字段

表名:orderInfo

列名:companySend,companyReceiver


先展示表结构,(手打了,见谅)

public class OrderInfo
    {
        public int id{ get; set; }
        public string Name { get; set; }
        public Nullable<int> companyId1{ get; set; }
        public Nullable<int> companyId2{ get; set; }

        [ForeignKey("companyId1")]
        public CompanyInfo company1{ get; set; }

        [ForeignKey("companyId2")]
        public CompanyInfo company2{ get; set; }

    }

public class CompanyInfo
{
public int id{ get; set; }
        public string Name { get; set; }
        
        public List<OrderInfo> order1 { get; set; }
        public List<OrderInfo> order2 { get; set; }
}

这里我们看见,对于order,我存在了两个关联company的字段。

如果进入codefirst,那么实际会出现问题。

大致是,对于companyid会出现4个字段,companyid1,companyid2,companyInfoid1,companyInfoid2


怎么解决这个问题呢?

我们先明白,出现这个问题,主要是order虽然申明了foreignkey和字段名称。但是系统不知道应该对应 order1还是order 2


解决这个问题,我们只需要这个:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //增加映射关系
            modelBuilder.Entity<Order>()
 .HasRequired(a => a.company1)
 .WithMany(u2 => u2.order1)
 .HasForeignKey(a => a.companyId1)
 .WillCascadeOnDelete(false);
            modelBuilder.Entity<Order>()
             .HasRequired(a => a.company2)
             .WithMany(u2 => u2.order2)
             .HasForeignKey(a => a.companyId2)
             .WillCascadeOnDelete(false);
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值