C# 实体框架模型中的更新列表
我有一个实体框架模型:C# 实体框架模型中的更新列表,c#,sql-server,asp.net-mvc,database,entity-framework,C#,Sql Server,Asp.net Mvc,Database,Entity Framework,我有一个实体框架模型: public class Application { [Key] public int ApplicationID { get; set; } public int PatentID { get; set; } ... //------------------------------------ public string ApplicationNumber { get; set; } public string
public class Application
{
[Key]
public int ApplicationID { get; set; }
public int PatentID { get; set; }
...
//------------------------------------
public string ApplicationNumber { get; set; }
public string Priority { get; set; }
public List<ApplicationPayment> Payments { get; set; }
= new List<ApplicationPayment>();
}
实体框架在ApplicationPayment
modelApplication\u ApplicationID
中为我创建其他外键
我在ApplicationPayment
表中添加了一个新实例,其中包含现有应用程序的编号:
但是当我试图显示这个ApplicationPayment
的表时,返回的是空表
我试图通过SQL Server Management Studio和假请求手动添加ApplicationPayment
。添加了新行,但ApplicationPayment列表仍然为空
假请求:
[HttpPut]
public void CreateApplicationPayment(int? id)
{
ApplicationPayment appPayment = new ApplicationPayment()
{
Amount = 80.0f,
Date = new DateTime(2017, 10, 25),
PaymentName = "payment",
PayNumber = 30,
TopicPart = 20
};
Application application = db.Applications.Find(id);
application.Payments.Add(appPayment);
db.SaveChanges();
}
如果希望EF自动填充集合属性,则该集合属性需要是虚拟的:
public virtual List<ApplicationPayment> Payments { get; set; }
这将导致EF加入相关的ApplicationPayment
s。然后需要使用SingleOrDefault
而不是Find
,因为Find
不适用于Include
。(Find
在命中数据库之前,首先在上下文中查找对象,因此无法解释可用的相关项。)请参见您正在使用PUT?你需要把数据映射到modal。,为什么有“=new…”行呢?我不认为模型真的是他们澄清Maxim评论的地方:ApplicationPayment需要引用特定的应用程序。尝试将:公共应用程序应用程序{get;set;}添加到ApplicationPayment类
public virtual List<ApplicationPayment> Payments { get; set; }
Application application = db.Applications.Include(m => m.ApplicationPayments).SingleOrDefault(m => m.Id == id);