EntityFrameworkCore 中的 Attach 方法

Attach 的坑

Model Filed Database Value Console Value
User Phone +123000000000 +12333333333
User Email null eeeeeee
User Id 1 1
dbcontext.Users.Add(new User()
    {
        UserName = "test1",
        CreatedAt = DateTime.Now
        Phone = "+1230000000"
    });
dbcontext.SaveChanges();

var user = new User()
{
    Id = 1,
    Phone = "+12333333333",
    Email = "eeeeeeee"
};
dbcontext.Users.Attach(user); 
//上面语句会抛异常,原因是dbcontext 已经跟踪了一个相同Id的实体,所以使用Attach注意当前的上下文


var user = new User()
{
    Id = 1,
    Phone = "+12333333333",
    Email = "eeeeeeee",
    UpdatedAt = DateTime.Now
};
var entryEntity = dbContext.Users.Attach(user1);

//entryEntity.State = EntityState.Unchanged; 有没有这句话结果是一样的
entryEntity.Property(p => p.Phone).IsModified = true;
entryEntity.Property(p => p.Email).IsModified = false;
dbContext.SaveChanges();

//数据库中只有明确标为`IsModified`为`true`的 `Phone`的值更改了,其余值保持不变

var item = dbContext.Users.FirstAsync().Result;
//item 的值和 user 中值完全相同 

var user = new User()
{
    Id = 1,
    Phone = "+12333333333",
    Email = "eeeeeeee",
    UpdatedAt = DateTime.Now
};
var entryEntity = dbContext.Users.Attach(user1);

entryEntity.State = EntityState.Modified;
entryEntity.Property(p => p.Phone).IsModified = true;
entryEntity.Property(p => p.Email).IsModified = false;
dbContext.SaveChanges();

//数据库中只有明确标为`IsModified`为`false`的 `Emial`的值没有更改,其余值都会做更改

var item = dbContext.Users.FirstAsync().Result;
//item 的值和 user 中值完全相同 

var user = dbContext.Users.FirstAsync().Result;
var userTemp = new User { Id = 1 };
dbContext.Users.Attach(userTemp);
//报异常,原因同例1
var user = dbContext.Users.AsNoTracking().FirstAsync().Result;
var userTemp = new User { Id = 1 };
dbContext.Users.Attach(userTemp);
//不报异常
posted @ 2019-05-10 15:14  大头大头灬下雨不愁  阅读(1334)  评论(0编辑  收藏  举报