C# 我可以在工作单元存储库模式中更新导航属性吗?
我的项目中有两个实体:C# 我可以在工作单元存储库模式中更新导航属性吗?,c#,asp.net,entity-framework,asp.net-web-api,unit-of-work,C#,Asp.net,Entity Framework,Asp.net Web Api,Unit Of Work,我的项目中有两个实体: public class A { public int Id { get; set; } public DateTime CreatedDateTime { get; set; } public virtual B B { get; set; } } public class B { public int Id { get; set; } public Nullable<DateTime> LastAli
public class A
{
public int Id { get; set; }
public DateTime CreatedDateTime { get; set; }
public virtual B B { get; set; }
}
public class B
{
public int Id { get; set; }
public Nullable<DateTime> LastAliveTime { get; set; }
public virtual ICollection<A> A { get; set; }
}
这会一直有效吗
这是更新B实体的LastAliveTime的正确方法,还是应该像下面这样初始化另一个存储库
var bService = unitOfWork.GetRepository<B>();
var bService=unitOfWork.GetRepository();
你不需要这么做
您必须使用即时加载(
Include(x=>x.B)
)或延迟加载。那你就不会有任何问题了 为什么每个实体类型都有存储库?假设virtual
意味着延迟加载,这取决于基础上下文生存期。如果上下文仍处于活动状态,当您调用ins.B
或ins.B
已加载时,它将工作。否则,当上下文被释放时,您将获得invalidoOperationException
,尝试加载B
。我需要对现有项目进行最小修复,正如@Dennis所提到的,如果我的上下文未被释放,到目前为止代码仍在工作,如果需要更新的虚拟财产是ICollection,则此操作将不起作用。
ins.B.LastAliveTime = DateTime.UtcNow;
var bService = unitOfWork.GetRepository<B>();