【问题标题】:Which approach to use on a provider with entity framework?在具有实体框架的提供者上使用哪种方法?
【发布时间】:2011-02-18 16:37:41
【问题描述】:

我有一堂课:

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();
    }
}

它不起作用,因为它们在不同的上下文中,Update 方法上的参数甚至没有被使用。但是,我可以从数据库中获取对象并使用参数对象一一更改字段,然后保存更改。

我该怎么办?

  • 更新对象并保存?
  • 在提供者上只保留一个上下文?
  • 另一种方法?

【问题讨论】:

  • 对两种方法使用相同的上下文。这样做有什么挑战吗?

标签: c# entity-framework provider


【解决方案1】:

我从another question找到了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);
}

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 2013-11-03
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    相关资源
    最近更新 更多