上下文每个请求:如何更新实体 [英] Context Per Request: How to update Entity

查看:185
本文介绍了上下文每个请求:如何更新实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仓储类,如下图所示。有一个方法来获得实体对象 - GetPaymentByID。我检索支付对象,并在更改其PaymentType财产。但是,这并没有反映在DATABSE。我知道了原因 - SaveContextChanges方法使用一个新的环境。

我需要使用上下文每请求办法。因此,我在每一个方法创建新的上下文。

在这种情况下,我怎么能修改code成功地更新数据库?

注:客户端程序不应该使用ObjectContext的,因为在存储库可以与其它存储库来改变不使用实体框架

注意一个DataContext是轻量级的,不贵创建

 命名空间MyRepository
{


公共类MyPaymentRepository
{
    私人字符串connectionStringVal;
    公共MyPaymentRepository()
    {
        SqlConnectionStringBuilder sqlBuilder =新SqlConnectionStringBuilder();
        sqlBuilder.DataSource =。;
        sqlBuilder.InitialCatalog =LibraryReservationSystem;
        sqlBuilder.IntegratedSecurity = TRUE;

        //初始化EntityConnectionStringBuilder。
        EntityConnectionStringBuilder entityBuilder =新EntityConnectionStringBuilder();
        entityBuilder.Provider =System.Data.SqlClient的;
        entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
        entityBuilder.Metadata = @RES://*/MyEDMtest.csdl |高分辨率://*/MyEDMtest.ssdl |高分辨率://*/MyEDMtest.msl;

        connectionStringVal = entityBuilder.ToString();
    }




    公共MyEntityDataModelEDM.Payment GetPaymentByID(INT paymentID)
    {
        MyEntityDataModelEDM.Payment付款;
        使用(VAR myObjectContext2 =新MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {

            FUNC< MyEntityDataModelEDM.Payment,布尔> predicate =(P => p.PaymentID == paymentID);
            支付= myObjectContext2.Payments.SingleOrDefault(predicate);
        }
        返回付款;
    }


    公共无效SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
    {
        使用(VAR myObjectContext =新MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {
            myObjectContext.SaveChanges();
        }
    }


}


}
 

客户端

  MyRepository.MyPaymentRepository代表=新MyRepository.MyPaymentRepository();

        MyEntityDataModelEDM.Payment P2 = rep.GetPaymentByID(1);
        p2.PaymentType =TeSSS;
        rep.SaveContextChanges(P2);
 

阅读

  1. 添加/安装和实体的国家:<一href="http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx" rel="nofollow">http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

  2. <一个href="http://stackoverflow.com/questions/1063730/best-way-to-initialize-an-entity-framework-context">Best方法来初始化一个实体的框架范围内?

  3. <一个href="http://stackoverflow.com/questions/10164949/entity-framework-4-1-how-to-work-with-per-call-life-time-data-context">Entity框架4.1:怎么每次通话续航时间数据的情况下一起工作

  4. <一个href="http://stackoverflow.com/questions/7678665/attaching-and-detaching-entities-from-context-correctly-in-ef4-1">Attaching和分离的背景下实体正确EF4.1

  5. <一个href="http://stackoverflow.com/questions/7457275/context-lifetime-management-in-repository-and-unit-of-work-pattern">Context生命周期管理的存储库和单位的工作模式

  6. 实体框架的多目标上下文

  7. <一个href="http://stackoverflow.com/questions/9398977/ef4-context-entry-isnt-available-to-change-an-entity-state">EF4 - Context.Entry不可更改实体状态

解决方案

您需要添加(如果数据是新的)或附加(如果该数据被编辑)对象上下文:

<一个href="http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx" rel="nofollow">http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

这些方针的东西:

 公共无效SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
{
    使用(VAR myObjectContext =新MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
    {
        //使用自己的逻辑来确定新实体
        myObjectContext.Entry(paymentEntity).State =
                (paymentEntity.PaymentID ==默认(INT))?
                               EntityState.Added:
                               EntityState.Modified;

        myObjectContext.SaveChanges();
    }
}
 

I have a repository class as shown below. There is a method to get entity object – GetPaymentByID. I am retrieving a Payment object and making a change to its PaymentType property. But this is not reflected in databse. I know the reason – the SaveContextChanges method uses a new context.

I need to use Context Per Request approach. Hence I am creating new context in each method.

In this scenario, how can I modify the code to successfully update the database?

Note: The client program should not use the ObjectContext because the repository can be changed with another repository that does not use Entity Framework.

Note: "A DataContext is lightweight and is not expensive to create"

namespace MyRepository
{


public class MyPaymentRepository
{
    private string connectionStringVal;
    public MyPaymentRepository()
    {
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
        sqlBuilder.DataSource = ".";
        sqlBuilder.InitialCatalog = "LibraryReservationSystem";
        sqlBuilder.IntegratedSecurity = true;

        // Initialize the EntityConnectionStringBuilder.
        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
        entityBuilder.Provider = "System.Data.SqlClient";
        entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
        entityBuilder.Metadata = @"res://*/MyEDMtest.csdl|res://*/MyEDMtest.ssdl|res://*/MyEDMtest.msl";

        connectionStringVal = entityBuilder.ToString();
    }




    public MyEntityDataModelEDM.Payment GetPaymentByID(int paymentID)
    {
        MyEntityDataModelEDM.Payment payment;
        using (var myObjectContext2 = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {

            Func<MyEntityDataModelEDM.Payment, bool> predicate = (p => p.PaymentID == paymentID);
            payment = myObjectContext2.Payments.SingleOrDefault(predicate);
        }
        return payment;
    }


    public void SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
    {
        using (var myObjectContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {
            myObjectContext.SaveChanges();
        }
    }


}


}

Client

        MyRepository.MyPaymentRepository rep = new MyRepository.MyPaymentRepository();

        MyEntityDataModelEDM.Payment p2= rep.GetPaymentByID(1);
        p2.PaymentType = "TeSSS";
        rep.SaveContextChanges(p2);

READING

  1. Add/Attach and Entity States: http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

  2. Best way to initialize an entity framework context?

  3. Entity Framework 4.1: how to work with per call life time data context?

  4. Attaching and detaching entities from context correctly in EF4.1

  5. Context lifetime management in repository and unit of work pattern

  6. Entity Framework Multiple Object Contexts

  7. EF4 - Context.Entry isn't available to change an Entity State

解决方案

You need to add (if the data is new) or attach (if the data is edited) the object to the context:

http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

Something along these lines:

public void SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
{
    using (var myObjectContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
    {
        // use your own logic for determining a "new" entity
        myObjectContext.Entry(paymentEntity).State = 
                (paymentEntity.PaymentID == default(int)) ?  
                               EntityState.Added :
                               EntityState.Modified;

        myObjectContext.SaveChanges();
    }
}

这篇关于上下文每个请求:如何更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆