Modifying a property on an entity in Entity Framework causes validation error

前端 未结 2 1930
生来不讨喜
生来不讨喜 2021-01-23 06:04

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.Newsletter         


        
相关标签:
2条回答
  • 2021-01-23 06:22

    Do not want to pollute your model with foriegn keys? Good! Read on. Instead you can override the SaveChanges method in NewsletterContext. Get all modified entities and using reflection, load all their lazy loaded properties and collections using the following sample syntax:

    db.Entry(newsletter).Reference(n => n.RequiredProp1).Load();
    db.Entry(newsletter).Collection(n => n.RequiredCollec1).Load();
    

    It won't be easy as it sounds, but once you are have written it, it would feel so good to see it work seamlessly :)

    0 讨论(0)
  • 2021-01-23 06:24

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题