简体   繁体   中英

Insert or Update with LINQ to Entity

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.

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.

public class JobDao : IDisposable {

    TNEntities context = new TNEntities();

    public Job LoadJob(int id)
    {
       return this.context.Jobs.First(c => c.id == id);
    }

    public void Save(){
       this.context.SaveChanges();
    }

    public void Dispose(){
        this.Context.Dispose();
    }
}

(of course you'll want to put a lot of that boilerplate code into a base class)

using(JobDao dao = new JobDao()) {
   Job j = dao.LoadJob(12);
   j.JobTitle = "Software Developer";
   dao.Save();
}

I would suggest you consider leaving a property in your application.xaml.cs like

public TNEntities context {get; private set;}

which has its TNEntities initalized at startup. It will make your life easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM