使用实体框架(C#)删除异常

时间:2010-02-12 17:08:54

标签: c# entity-framework

我遇到一些简单代码的问题,我正在将一些现有的代码从LINQ to SQL重构为Entity Framework。我正在测试我的保存和删除,删除真的让我烦恼:

[TestMethod]
public void TestSaveDelete()
{
    ObjectFactory.Initialize(x =>
    {
        x.For<IArticleCommentRepository>().Use<ArticleCommentRepository>();
    });

    PLArticleComment plac = new PLArticleComment();
    plac.Created = DateTime.Now;
    plac.Email = "myemail";
    plac.Name = "myName";
    plac.Text = "myText";
    plac.Title = "myTitle";

    IArticleCommentRepository acrep = ObjectFactory.GetInstance<IArticleCommentRepository>();
    try
    {
        PortalLandEntities ple = new PortalLandEntities();
        int count = ple.PLArticleComment.Count();
        acrep.Save(plac);
        Assert.AreEqual(ple.PLArticleComment.Count(), count + 1);
        //PLArticleComment newPlac = ple.PLArticleComment.First(m => m.Id == plac.Id);
        //ple.Attach(newPlac);
        acrep.Delete(plac);
        Assert.AreEqual(ple.PLArticleComment.Count(), count + 1);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

每当我尝试运行此代码时,我在delete语句中得到一个异常,告诉我它不包含在当前的ObjectStateManager中。请注意我的Save和delete都是这样的:

public void Delete(PLCore.Model.PLArticleComment comment)
{
    using (PortalLandEntities ple = Connection.GetEntityConnection())
    {
        ple.DeleteObject(comment);
        ple.SaveChanges();
    }
}

public void Save(PLCore.Model.PLArticleComment comment)
{
    using (PortalLandEntities ple = Connection.GetEntityConnection())
    {
        ple.AddToPLArticleComment(comment);
        ple.SaveChanges();
    }
}

和连接东西:

public class Connection
{
    public static PortalLandEntities GetEntityConnection()
    {
        return new PortalLandEntities();
    }
}

关于如何使其发挥作用的任何想法?

1 个答案:

答案 0 :(得分:1)

您无法从一个ObjectContext加载实体(在您的情况下,ObjectContextPortalLandEntities的实例),然后将其从另一个ObjectContext中删除,除非您将它从第一个分离并将其连接到第二个。如果你一次只使用一个ObjectContext,你的生活会变得更加简单。如果您不能这样做,则必须首先手动Detach然后Attach,同时跟踪哪些实体与ObjectContext连接。

如何在Connection上使用DI:将其设为非静态。

public class Connection
{
    private PortalLandEntities _entities;

    public PortalLandEntities GetEntityConnection()
    {
        return _entities;
    }

    public Connection(PortalLandEntities entities)
    {
        this._entities = entities;
    }
}

然后根据请求使用DI容器。大多数人通过控制器工厂来做这件事。