简体   繁体   English

实体框架4:添加和保存实体的最佳方法是什么?

[英]Entity Framework 4: What is the best way to add and save an entity?

I have a BaseRepository class that is used by all repositories to save entities (new or updated): 我有一个BaseRepository类,所有存储库都使用该类来保存实体(新的或更新的):

public abstract class BaseRepository
{
    protected void Add<T>(T source, CliCEntities context, bool isNew, EntityState state) where T : class
    {
        if (isNew)
        {
            context.CreateObjectSet<T>().AddObject(source);
        }
        else
        {
            if (state == EntityState.Detached)
            {
                context.CreateObjectSet<T>().Attach(source);
            }
        }
    }

    protected void Save(MyEntities context)
    {
        context.SaveChanges();
    }
}

It's called like this: 叫做:

public class MyEntityRepository : BaseRepository
{
    public void Add(MyEntity source, MyEntities context)
    {
        base.Add(source, context, source.ID == Guid.Empty, source.EntityState);
    }

    public void Save(MyEntities context) {
        base.Save(context);
    }
}

The issue 问题

When the base.Save() is called, there's no difference to the data, EntityState is unchanged. 调用base.Save()时,数据没有区别,EntityState不变。 I assume this is because the load was on a different Context instance, so the current Context doesn't know about any changes. 我认为这是因为加载是在另一个Context实例上,所以当前Context不知道任何更改。

How can I change the above code so that my source instance has EntityState Modified (so that it would work)? 如何更改上面的代码,以便我的源实例具有EntityState Modified(以便可以正常工作)?

I found a solution: 我找到了解决方案:

protected void Add<T>(T source, CliCEntities context, bool isNew, EntityState state) where T : class
{
    if (isNew)
    {
        context.CreateObjectSet<T>().AddObject(source);
    }
    else
    {
        if (state == EntityState.Detached)
        {
            context.CreateObjectSet<T>().Attach(source);

            context.ObjectStateManager.ChangeObjectState(source, EntityState.Modified);
        }
    }
}

The big difference is this: 最大的区别是:

context.ObjectStateManager.ChangeObjectState(source, EntityState.Modified); context.ObjectStateManager.ChangeObjectState(source,EntityState.Modified);

That way I can change the EntityState of the source object, so it's actually updated. 这样,我可以更改源对象的EntityState,因此实际上已对其进行了更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM