zoukankan      html  css  js  c++  java
  • 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);
            }



  • 相关阅读:
    Windows中Lua环境配置记录
    《Programming in Lua 3》读书笔记(四)
    《Programming in Lua 3》读书笔记(三)
    《Programming in Lua 3》读书笔记(一)
    C++中的struct
    POJ 1080 Human Gene Functions
    POJ 3176 Cow Bowling
    POJ 2533 Longest Ordered Subsequence
    POJ 1260 Pearls
    POJ 1836 Alignment
  • 原文地址:https://www.cnblogs.com/hanjun0612/p/9779906.html
Copyright © 2011-2022 走看看