实体框架一对多和多对多关系

时间:2016-08-20 14:54:29

标签: c# entity-framework

我目前正在学习实体框架,并且在几天内完成了这项任务的失败......我想实现以下数据库方案:

TableA:
ClassA_ID
ClassB_ID(foreign key - one to one)

TableATableB:(one-to-many relationship)
ClassA_ID
ClassB_ID

TableB:
ClassA_ID(foreign key - one to one)
ClassB_ID

所以我实际上想要从A类到B类的特定的一对一关系以及从ClassA到ClassB的一对多关系。

我的C#代码如下所示:

A类:

public static int idcounter;
[Key]
public int id { get; set; }
public virtual List<ClassB> allClassB { get; set; }
public virtual ClassB currentClassB { get; set; }
public int? currentClassBID { get; set; }

public ClassA(){
    idcounter++;
    id = idcounter;
    allClassB = new List<ClassB>();
    currentClassB = new ClassB();
    currentClassBID = currentClassB.id;
    MyContext.add(this);
}

B组:

public static int idcounter;
[Key]
public int id { get; set; }
public virtual ClassA owner { get; set; }
public int? ownerID { get; set; }

public ClassB(ClassA a){
    idcounter++;
    id = idcounter;
    owner = a;
    ownerID =  a.id;
}

MyContext:

public static void add(ClassA a)
    {
        using (MyContext context = new MyContext ())
        {
            context.setB.Add(a.currentClassB);
            context.setA.Add(a);
            context.SaveChanges();           
        }
    }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ClassA>().HasOptional(x => x.currentClassB ).WithMany().HasForeignKey(x => x.currentClassBID ).WillCascadeOnDelete(false);
        modelBuilder.Entity<ClassB>().HasOptional(x => x.ClassA).WithMany(x => x.allClassB).HasForeignKey(x => x.ownerID).WillCascadeOnDelete(false) ;
    }

它非常类似于这个问题 Entity Framework Code First: How can I create a One-to-Many AND a One-to-One relationship between two tables? 但是我在保存时只收到一个循环异常。

Unable to determine a valid ordering for dependent operations. Dependencies may 
exist due to foreign key constraints, model requirements, or store-generated 
values.

之后非常奇怪
context.setA.Add(a);

它将currentClassB添加到allClassB中,而我没有提到过......当我不这样做时,它突然就这样做了

allClassB = new List<ClassB>();

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您必须使用InverseProperty,如下所示。

[InverseProperty("allClassB")]
public virtual ClassB currentClassB { get; set; }
public int? currentClassBID { get; set; }

DataAnnotations - InverseProperty Attribute: