【发布时间】:2020-11-28 09:10:08
【问题描述】:
以下是课程:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Child> Childs { get; set; }
public IEnumerable<ParentLog> Logs { get; set; }
}
public class ParentLog
{
public int Id { get; set; }
public DateTime On { get; set; }
public string Note { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public IEnumerable<ChildLog> Logs { get; set; }
}
public class ChildLog
{
public int Id { get; set; }
public DateTime On { get; set; }
public string Note { get; set; }
public int ChildId { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
}
在DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>().HasMany(a => a.Childs);
modelBuilder.Entity<Parent>().HasMany(a => a.Logs);
modelBuilder.Entity<Child>().HasMany(a => a.Logs);
}
这个想法是当父母和孩子被保存时,父母和孩子的日志条目也被保存。这行得通。
保存代码:
DateTime now = DateTime.Now;
foreach (var a in parents)
{
a.Logs = new List<ParentLog>();
a.Logs.Add(new ParentLog
{
On = now,
Note = "Created",
Name = a.Name
});
foreach(var b in a.Childs)
{
b.Logs = new List<ChildLog>();
b.Logs.Add(new ChildLog
{
On = now,
Note = "Created",
Name = b.Name,
ParentId = b.ParentId //not needed with the Accepted Answer.
});
}
}
int recordsAffected = new ParentRepository().SaveParents(parents);
public int SaveParents(List<Parent> items)
{
foreach(var item in items)
{
_db.Parents.Add(item);
}
return _db.SaveChanges();
}
我遇到的问题是ChildLog.ParentId。它没有预期值的值,我想是来自Child.ParentId。
我的问题,如何解决?
【问题讨论】:
-
由于
ChildLog与实体Parent没有任何直接关系,只需从Child实体保存更改日志...您必须将Child.ParentId属性值传递给@987654332 @属性。 -
Luis,我也试过了,为 ChildLog.ParentId 保存的值仍然是 0 ,而对于 ChildLog.ChildId,它是实际的 Child.Id。
-
您没有显示您遇到问题的保存代码。
-
Gert Arnold,我刚刚添加了保存代码。
-
没有显示最重要的部分:所有这些对象都是新的吗?我猜他们是,所以
ParentId根本还没有它的生成值。您只能在保存后分配它们。
标签: c# entity-framework