gpt4 book ai didi

entity-framework - Entity Framework 4.3 CF 多对多关系保存对象?

转载 作者:行者123 更新时间:2023-12-04 05:46:32 27 4
gpt4 key购买 nike

使用 EF 4.3 代码优先方法创建多对多关系时,我无法将数据保存到连接表,也无法使用将对象保存到 Icollection 来填充此表的任何示例...这是我的示例:

型号

public class Hospital
{
//PK
[Key]
public int Id { get; set; }

public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }

//FK
public virtual ICollection<Operator> Operators { get; set; }

}

public class Operator
{
//PK
[Key]
public int Id { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }

//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
}

public class Project: DbContext
{
public DbSet<Hospital> Hospitals { get; set; }
public DbSet<Operator> Operators { get; set; }
}

Controller
public void AddOperater()
{

Hospital h = new Hospital();
h = db.Hospitals.Single(a=>a.Id ==1);

var o = new Operator();
o.FirstName = "John";
o.LastName = "Doe";
o.Dob = new DateTime(1988,2,12);
o.Email = "johndoe@gmail.com";
o.Hospitals.Add(h);

db.SaveChanges();
}

使用这种方法,我在这里不断收到错误: o.Hospitals.Add(h);即使我的 Hospital 实例充满了数据。如何将数据保存到两个表中, dbo.Operatorsdbo.OperatorHospital哪个是关系表?

最佳答案

o.Hospitals.Add(h) 将失败,因为该列表是一个空列表。您不能在空列表上调用 Add()。通常大多数人通过在实体的构造函数中实例化列表来解决这个问题......就像这样......由于CSharp问题,当前行正在爆炸。

public class Hospital
{
//PK
[Key]
public int Id { get; set; }

public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }

//FK
public virtual ICollection<Operator> Operators { get; set; }

public Hospital()
{
Operators = new List<Operator>();
}

}


public class Operator
{
//PK
[Key]
public int Id { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }

//FK
public virtual ICollection<Hospital> Hospitals { get; set; }

public Operator()
{
Hospitals = new List<Hospital>();
}

}

关于entity-framework - Entity Framework 4.3 CF 多对多关系保存对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com