这两个实体是一对多的关系(由代码第一流畅的api构建).
public class Parent
{
public Parent()
{
this.Children = new List<Child>();
}
public int Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在我的WebApi控制器中,我有动作创建父实体(工作正常)并更新父实体(有一些问题).更新操作如下所示:
public void Update(UpdateParentModel model)
{
//what should be done here?
}
Run Code Online (Sandbox Code Playgroud)
目前我有两个想法:
获取一个名为existingby 的跟踪父实体model.Id,并将值model逐个赋值给实体.这听起来很愚蠢.在model.Children我不知道哪个孩子是新的,哪个孩子被修改(甚至删除).
通过创建一个新的父实体model …
这令人沮丧.这是一对相关对象,由数据库优先实体框架生成:
public partial class DevelopmentType
{
public DevelopmentType()
{
this.DefaultCharges = new HashSet<DefaultCharge>();
}
public System.Guid RowId { get; set; }
public string Type { get; set; }
public virtual ICollection<DefaultCharge> DefaultCharges { get; set; }
}
public partial class DefaultCharge
{
public System.Guid RowId { get; set; }
public decimal ChargeableRate { get; set; }
public Nullable<System.Guid> DevelopmentType_RowId { get; set; }
public virtual DevelopmentType DevelopmentType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我要调用以保存DevelopmentType的代码 - 它涉及到automapper,因为我们将实体对象与DTO区分开来:
public void SaveDevelopmentType(DevelopmentType_dto dt)
{ …Run Code Online (Sandbox Code Playgroud) 假设您的实体中有这些类.
public class Parent
{
public int ParentID { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public int ChildID { get; set; }
public int ParentID { get; set; }
public virtual Parent Parent { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并且您有一个用户界面来更新Parent它Children,这意味着如果用户添加新的,Child那么您必须插入,如果用户编辑现有的Child则需要更新,如果用户删除了Child则必须删除.现在很明显,如果您使用以下代码
public void Update(Parent obj)
{
_parent.Attach(obj);
_dbContext.Entry(obj).State = EntityState.Modified;
_dbContext.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
它将无法检测到内部的更改,Child因为EF无法检测到导航属性中的更改.
我一直在问这个问题4次,得到的答案很复杂.那么实际上可以做到这一点而不会变得复杂吗?这个问题可以通过分离之间的用户界面解决问题Parent和Child,但我不想因为两者合并Child,并 …
我需要知道如何更新和删除数据库中的记录.我知道如何添加记录但无法更新和删除数据库中的记录.
namespace Ex.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class MyEntities : DbContext
{
public MyEntities()
: base("name= MyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Friend> Friend { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
-
控制器
// POST: /Home/Edit/5
[HttpPost]
public ActionResult Edit(int id, Friend f)
{
try
{
// TODO: Add update logic here
myEntities.Friend.Attach(f);// Doesn't work.. How to update ?
myEntities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
} …Run Code Online (Sandbox Code Playgroud)