c# – Entity Framework直接更新虚拟属性而不创建新记录
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – Entity Framework直接更新虚拟属性而不创建新记录,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2760字,纯文字阅读大概需要4分钟。
内容图文
这是一个简单的实体:
public class Customer : Entity
{
public virtual Location Location { get; set; }
}
现在假设我们已经有了一个客户:
var customer = new Customer() {Location = new Location("China")};
现在我们要更新他的位置:
var customer = context.Customers.First(x => x.Location.Country == "China");
customer.Location = new Location("America");
context.SaveChanges();
现在,当我查看数据库时,位置记录“中国”尚未删除:数据库现在有两个位置记录与一个客户记录关联.
这个问题的原因是我在Customer.Location属性上使用虚拟关键字,当我从数据库查询客户实体时,我没有使用Include方法来加载Location属性,我也没有使用任何访问懒得加载它.因此,EF无法跟踪并知道应删除中国位置实体.
我认为我用于更新虚拟属性的方法符合直觉.我想更新一个属性,然后只使用更新指令“entity.xxx = …”,添加被迫使用属性或方法调用的一些访问,而加载“entity.xxx”是不直观的.
所以我正在寻找一种更好的方法直接替换实体的虚拟财产.有什么建议?
解决方案更新
我找到两种方法来做到这一点,
首先你可以使用Identifying relation(推荐).
另一种方法可以使用ObjectContext.DeleteObject方法,下面是示例代码:
public static class EFCollectionHelper
{
public static void UpdateCollection<T, TValue>(this T target,
Expression<Func<T, IEnumerable<TValue>>> memberLamda, TValue value)where T : Entity
{
var memberSelectorExpression = (MemberExpression)memberLamda.Body;
var property = (PropertyInfo)memberSelectorExpression.Member;
var oldCollection = memberLamda.Compile()(target);
oldCollection.ClearUp();
property.SetValue(target, value, null);
}
public static void ClearUp<T>(this IEnumerable<T> collection)
{
//Convert your DbContext to IObjectContextAdapter
var objContext = ((IObjectContextAdapter) Program.DbContext).ObjectContext;
for (int i = 0; i < collection.Count(); i++)
{
objContext.DeleteObject(collection.ElementAt(i));
}
}
}
然后你可以简单地编写如下代码:
customer.UpdateCollection(x => x.Locations, null);
解决方法:
不完全确定你想要什么,但这就是我得到的.
您现在获得两个位置的原因是因为您使用了新位置(“美国”);你真的添加了对新位置的引用(EF不知道中国是否被其他客户使用,并且在该类型的查询中永远不会删除它)
现在,如果你说.
customer.Location.Country = "America"
中国将被美国覆盖,因为我们正在与特定地点的财产合作.
阅读关于这个问题的评论,这是一些额外的内容
如果要完全更新位置(新位置(“一些新位置”)).然后你会这样做.
Location oldLocation = customer.Location;
Location newLocation = new Location("America");
//Check if the new location country !exist
if(!context.Locations.Any(a=> a.Country == newLocation.Country))
{
//If it don't exist then add it (avoiding the location duplicate)
customer.Location = newLocation;
//If its important to delete the old location then do this
//(important to do after you removed the dependency,
//thats why its after the new location is added)
context.Locations.Remove(oldLocation)
//Finally Save the changes
context.SaveChanges();
}
内容总结
以上是互联网集市为您收集整理的c# – Entity Framework直接更新虚拟属性而不创建新记录全部内容,希望文章能够帮你解决c# – Entity Framework直接更新虚拟属性而不创建新记录所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。