在Entity Framework中修改实体上的属性会导致验证错误 [英] Modifying a property on an entity in Entity Framework causes validation error

查看:143
本文介绍了在Entity Framework中修改实体上的属性会导致验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图简单地加载实体,修改一个属性,然后将其保存回数据库。

  var db = new NewsletterContext(); 
var newsletter = db.Newsletters.Find(x => x.ID == newsletterID);
newsletter.SomeProperty = 5;
db.SaveChanges();

这会导致验证错误,因为newsletter对象中有一些属性是必需的,显然没有加载当我做一个 Find()



我可以使用 Include()为每个必需的属性,然后是一个 Where()

  var db = new NewsletterContext(); 
var newsletter = db.Newsletters.Include(x => x.RequiredProp1)
.Include(x => x.RequiredProp2).Include(x => x.RequiredProp3)
.Where(x => x.ID == newsletterID)
.FirstOrDefault();
db.SaveChanges();

这不是一个非常优雅的解决方案,如果我添加更多必需的属性到通讯对象。



有更好的解决方案吗?

解决方案

实体框架将在进行验证时禁用延迟加载。因此,如果您对导航属性进行了必需的验证,验证将失败。您可以修改与导航属性相关的标量属性。

  public class Foo 
{

[必需]
public int? RequiredScalarId {get;组; }

public virtual Bar RequiredNavigationalProp {get;组; }
}


I am trying to simply load an entity, modify a property and then save it back to the database.

var db = new NewsletterContext();
var newsletter  = db.Newsletters.Find(x => x.ID==newsletterID); 
newsletter.SomeProperty = 5;
db.SaveChanges();

This causes a validation error as there are some properties on the newsletter object which are required and apparently not loaded when I do a Find().

I can solve this using an Include() for each required property followed by a Where():

var db = new NewsletterContext();
var newsletter  = db.Newsletters.Include(x => x.RequiredProp1)
                    .Include(x => x.RequiredProp2).Include(x => x.RequiredProp3)
                    .Where(x => x.ID==newsletterID)
                    .FirstOrDefault(); 
db.SaveChanges();

This isn't a very elegant solution and will break if I add more required properties to the Newsletter object.

Is there a better solution?

解决方案

Entity framework will disable lazy loading when doing the validation. Hence if you put required validation on navigational properties the validation will fail. You can decorate the scalar property related to the navigational property instead.

public class Foo
{

    [Required]
    public int? RequiredScalarId { get; set; }

    public virtual Bar RequiredNavigationalProp { get; set; }
}

这篇关于在Entity Framework中修改实体上的属性会导致验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆