gpt4 book ai didi

c# - 如何使用 EF 将对象保存到数据库并从数据库中创建主键?

转载 作者:行者123 更新时间:2023-11-30 16:21:26 29 4
gpt4 key购买 nike

我正在使用 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;
}

我该怎么做?

最佳答案

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。

关于c# - 如何使用 EF 将对象保存到数据库并从数据库中创建主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13249888/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com