3

我正在使用 C#、.NET Framework 4.0 开发 WCF JSon Web 服务,Entity Framework用于访问数据库。

我必须创建一个新EReportDB.EReport对象,填充它,将其保存在数据库中并获取它的新 pk EReportDb.Ereport.eReportId

这是我的代码,但我不知道该怎么做:

    public bool SaveEReport(EReportContract eContractReport)
    {
        if (eContractReport == null)
            throw new ArgumentNullException("eContractReport", "SaveEReport: eReport is null");

        using (EReportDB.EReportEntities context = new EReportDB.EReportEntities())
        {
            EReportDB.EReport eReport = new EReportDB.EReport();
            eReport.orderId = eContractReport.orderId;
            eReport.timeIn = DateTime.Parse(eContractReport.timeIn, new CultureInfo("en-GB", false));
            eReport.timeOut = DateTime.Parse(eContractReport.timeOut, new CultureInfo("en-GB", false));
            eReport.isProducFact = eContractReport.isProducFact;
            /*
              ..snip..
            */
            eReport.olPkSizeRs_ = eContractReport.olPkSizeRs;
            eReport.olPkWeightRs = eContractReport.olPkWeightRs;
        }
        return false;
    }

我怎样才能做到这一点?

4

2 回答 2

2
int id = 0; // assuming the datatype for eReportId is int

using (EReportDB.EReportEntities objectContext = new EReportDB.EReportEntities())
{
   EReportDB.EReport eReport = new EReportDB.EReport();
   eReport.orderId = eContractReport.orderId;
   eReport.timeIn = DateTime.Parse(eContractReport.timeIn, new CultureInfo("en-GB", false));
   eReport.timeOut = DateTime.Parse(eContractReport.timeOut, new CultureInfo("en-GB", false));
   eReport.isProducFact = eContractReport.isProducFact;
   /*
     ..snip..
   */
   eReport.olPkSizeRs_ = eContractReport.olPkSizeRs;
   eReport.olPkWeightRs = eContractReport.olPkWeightRs;

   objectContext.AddObject(eReport); // method to insert the entity 
   objectContext.SaveChanges();
   id = eReport.eReportId;

   transaction.Complete();
}

id 是插入记录的 PK。

于 2012-11-06T11:34:15.127 回答
1

EF已经为你填好了。打电话

context.AddObject(eReport); 
context.Save(); 

在你的块的末尾,using你会找到你的钥匙eReport.eReportId

于 2012-11-06T11:33:57.570 回答