使用 LINQ to Entity 插入或更新
我正在尝试使用 Linq to Entity 作为新项目的 DAL。
在我的 DAL 中,我有这个方法来获取作业实体
public Job LoadJob(int id)
{
Job job = new Job();
using (TNEntities context = new TNEntities())
{
var jobEntity = (from c in context.Jobs
where c.id == id
select c).First();
job = (Job)jobEntity;
}
return job;
}
,我在程序中使用作业实体,然后我想保存它:
我尝试了一些不同的方法,但当前我的方法看起来像这样(它不起作用)
public void SaveJob(Job job)
{
using (TNEntities context = new TNEntities())
{
context.Jobs.AddObject(job);
context.SaveChanges();
}
}
我尝试过 context.jobs.attach(job) ,它不会引发错误,但不会更新我的作业。我认为这是因为作业脱离了上下文,因为它超出了使用上下文的范围。但我不确定如何重新附加它,以便它更新我在第一种方法中选择的作业。
I am trying to use Linq to Entity as my DAL for a new project.
In my DAL I have this method to get the Job Entity
public Job LoadJob(int id)
{
Job job = new Job();
using (TNEntities context = new TNEntities())
{
var jobEntity = (from c in context.Jobs
where c.id == id
select c).First();
job = (Job)jobEntity;
}
return job;
}
I use the Job entity in my program and then I would like to save it:
I have tried a few different things, but currenlt my method looks like this (it does not work)
public void SaveJob(Job job)
{
using (TNEntities context = new TNEntities())
{
context.Jobs.AddObject(job);
context.SaveChanges();
}
}
I have tried context.jobs.attach(job) which does not throw an error but it does not update my Job. I assume its because the Job is out of Context as its out of scope of the using context. But Im not sure how to re-attach it so it updates the job that I selected in my first method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理想情况下,您希望从上下文中读取作业,进行更改,然后在您最初读取作业的同一上下文上调用 SaveChanges。可能(应该)可以将修改后的实体附加到新上下文,并将其状态设置为已修改,但我发现这种方法会滥用修改后的子对象。
一种更简单的方法是将所有这些操作放在一个 DataAccess 对象中,该对象具有一个
TNEntities
上下文实例,并使用它来读取作业实体并保存更改。(当然,您需要将大量样板代码放入基类中)
Ideally, you want to read your job from a context, make changes, then call SaveChanges on the same context you originally read it from. It might (should) be possible to attach the modified entity to a new context, and set its status to modified, but I've found modified child objects are mistreated with this approach.
One of the easier approaches is to have all of these operations in a DataAccess object that has one instance of your
TNEntities
context, and uses it to read your job entity, and save changes.(of course you'll want to put a lot of that boilerplate code into a base class)
我建议您考虑在 application.xaml.cs 中保留一个属性,例如
在启动时初始化其 TNEntities。它会让你的生活更轻松。
I would suggest you consider leaving a property in your application.xaml.cs like
which has its TNEntities initalized at startup. It will make your life easier.