首页 新闻 赞助 找找看

关于EF的常见问题?

0
[待解决问题]

一、.AsNoTracking()带查询后遍历
foreach遍历结果集合

Student student= new Student ();
student.ID = item.ID;
student.ReportStatus = true;
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
不然会报错
"Attaching an entity of type XXX failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."}
二、更新实体前要获取实体,不然其余字段会被清空
错误实例

Student student=new Student();
student.ID=ID;
student.ReportStatus = true;
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
正确实例
var student= db.Students.Where(p => p.ID == item.ID).FirstOrDefault();
student.ReportStatus = true;
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();

三、EF实体decimal默认只保留小数点后两位的问题
解决方法:在创建DbContext时,重写DbContext.OnModelCreating()方法;然后通过如下方法指定精度:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//解决DbContext保存decimal类型数据到数据库,默认只会保存小数点后的前2位小数,其余均置0的问题,这样就会保存小数点7位了
modelBuilder.Entity<Models_VideoDeviceInfo>().Property(p => p.LongitudeX).HasPrecision(18, 7);
}
复制代码

cker90的主页 cker90 | 菜鸟二级 | 园豆:258
提问于:2021-04-15 08:32
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册