如何使用wvs和state获取想要的数据
发布网友
发布时间:2023-06-25 17:21
我来回答
共1个回答
热心网友
时间:2024-11-16 03:17
1. 让你有要排除的属性集合的:var excluded = new[] { "property1", "property2" };
随着EF5在NET 4.5中你可以这样做:var entry = context.Entry(obj);
entry.State = EntityState.Modified;
foreach (var name in excluded)
{
entry.Property(name).IsModified = false;
}
EF5对.NET 4.5,它允许一个属性被设置为即使它已经被设置为修改不修改的新函数。 ,EF 4.3.1或EF5上NET 4中你可以这样做,而不是:var entry = context.Entry(obj);
foreach (var name in entry.CurrentValues.PropertyNames.Except(excluded))
{
entry.Property(name).IsModified = true;
}
2. 你不能定义这样的异常。作为modified不过,您可以标记一个属性:context.Entry(obj).Property(o => o.Property3).IsModified = true;
context.Entry(obj).Property(o => o.Property4).IsModified = true;
// etc.
请注意,设置IsModified至false不支持,一旦你已经标志着整个实体的状态Modified。 你的目的我真的宁愿从数据库中加载实体 CodeGo.net,然后更新正常的更改轨迹:var objInDB = context.Objects.Single(o => o.Id == obj.Id);
obj.Property1 = objInDB.Property1;
obj.Property2 = objInDB.Property2;
context.Entry(objInDB).CurrentValues.SetValues(obj);
context.SaveChanges();
3. 这个问题已经很好地回答了,但我想任何人谁愿意它提供。 此代码为EF 4.3.1开发//You will need to import/use these namespaces
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
//Update an entity object's specified columns, comma separated
//This method assumes you already have a context open/initialized
public static void Update<T>(this DbContext context, T entityObject, params string[] properties) where T : class
{
context.Set<T>().Attach(entityObject);
var entry = context.Entry(entityObject);
foreach(string name in properties)
entry.Property(name).IsModified = true;
context.SaveChanges();
}
用法示例using (FooEntities context = new FooEntities())
{
FooEntity ef = new FooEntity();
//For argument's sake say this entity has 4 columns:
// FooID (PK), BarID (FK), Name, Age, CreatedBy, CreatedOn
//Mock changes
ef.FooID = 1;
ef.Name = "Billy";
ef.Age = 85;
context.Update<FooEntity>(ef, "Name", "Age"); //I only want to update Name and Age