Entity Framework Attach/Update confusion (EF Core)

前端 未结 2 781
予麋鹿
予麋鹿 2021-02-19 06:06

As I understand, when \"Update\" is called, every property within a specific entity is modified.

The \"Attach\" method, on the other hand, starts the entity off in the

2条回答
  •  花落未央
    2021-02-19 06:50

    Consider the following code:

    students entity = new students() {
        Id = 1,
        City = "New York",
        Name = "Sam"
    };
    using(SomeContext ctx = new SomeContext())
    {
        ctx.Entry(entity).State = EntityState.Modified;
        ctx.SaveChanges();
    }
    

    Assuming we have a record with id = 1 in the database, the above code will update that entity in the database.

    Attach is used when you know that an entity already exists in the database but want to make some changes while change state to modified when you have already made the changes.

提交回复
热议问题