简体   繁体   中英

What's the difference between the following ways of instantiating an entity?

What's the difference between the following ways of instantiating an entity? Considering Student is table in the database.

Student stud
using (var ctx = new SchoolDBEntities())
    {
        stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>();
    }

using (var dbCtx = new SchoolDBEntities())
    {
        var student = new Student();
    }

Is it just difference in style or is there some other difference I am missing?

In the first way, the object is still attached to the context. You'd do that to update an entity, the next one, you'll have to add the object to context to save, usually done for adding new records.

in the first approach, the stud is pulled from the database, and still attached to the context. If you made changes, and called db.SaveChanges() , those changes would be reflected in the database.

The second approach is simply creating a new instance of Student . You'd have to call db.Students.Add(student) to add it to the database. You don't need the using statement with this approach, until you wanted to add it.

Is it just difference in style or is there some other difference I am missing?

One is still linked to the context, the other is just an object outside of the database, until you add it.

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