首页 > 代码库 > MVC02

MVC02

1、在EF5.0修改实体的时候,出现“对一个或多个实体的验证失败。有关详细信息,请参见“EntityValidationErrors”属性这个错误db.Configuration.ValidateOnSaveEnabled = false;  int count = db.SaveChanges();  db.Configuration.ValidateOnSaveEnabled = true;

2、   DbQuery<User> dbQuery = db.Users.Where(u => u.uLoginName == "刘德华").OrderBy(u => u.uName).Take(2) as System.Data.Entity.Infrastructure.DbQuery<User>;       User usr01 = dbQuery.FirstOrDefault();

3、 连接查询(生成 inner join IQueryable<UsersAddress> addrs = db.UsersAddresses.Include("User").Where(a => a.udId == 1);  IQueryable<Msg> msgs = db.Msgs.Include("User").Include("User1"); //2个外键

4、官方推荐的 修改方式(先查询,再修改) 5、自己优化的 修改方式(创建对象,直接修改)    User usr = new User() { uId = 8,uName="小白~~~"};   DbEntityEntry<User> entry = db.Entry<User>(usr);   entry.State = System.Data.EntityState.Unchanged;    entry.Property("uName").IsModified = true;    db.SaveChanges(); 6、            User u = new User() { uId = 10 };             db.Users.Attach(u);             db.Users.Remove(u);

            /*                 也可以使用 Entry 来附加和 修改                 DbEntityEntry<User> entry = db.Entry<User>(u);                 entry.State = System.Data.EntityState.Deleted;              */             db.SaveChanges() 7、