C# 在具有实体框架的提供者上使用哪种方法?
我有一门课:C# 在具有实体框架的提供者上使用哪种方法?,c#,entity-framework,provider,C#,Entity Framework,Provider,我有一门课: public class Tool { [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public Int64 ID { get; set; } [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [Data
public class Tool
{
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public Int64 ID { get; set; }
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public string Name { get; set; }
}
我的提供者有两种方法:
public IEnumerable<Tool> GetFirst()
{
using (var db = new Entitites())
{
return db.Tools.FirstOrDefault();
}
}
public void Update(Tool o)
{
using (var db = new Entities())
{
db.Tools.SaveChanges();
}
}
public IEnumerable GetFirst()
{
使用(var db=new Entitites())
{
返回db.Tools.FirstOrDefault();
}
}
公共作废更新(工具o)
{
使用(var db=new Entities())
{
db.Tools.SaveChanges();
}
}
它不起作用,因为它们在不同的上下文中,甚至没有使用Update
方法上的参数。但是,我可以从数据库中获取对象,并使用参数对象逐个更改字段,然后保存更改
我该怎么办
- 是否更新对象并保存
- 在提供者上只保留一个上下文
- 另一种方法
attach
方法非常相似
using (var db = new Entitites())
{
// Attach the object on this context
db.Attach(tool);
// Change the state of the context to ensure update
db.ObjectStateManager.GetObjectStateEntry(tool).SetModified();
// ClientWins, flawless victory
db.Refresh(RefreshMode.ClientWins, tool);
}
对两种方法使用相同的上下文。这样做有什么挑战吗?