我正在使用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;
}
我该怎么做?
答案 0 :(得分: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。
答案 1 :(得分:1)
EF已经为您填补了空缺。 只需致电
context.AddObject(eReport);
context.Save();
在using
区块的末尾,您会在eReport.eReportId
找到您的密钥。