EF: Validation failing on update when using lazy-loaded, required properties

后端 未结 8 2045
栀梦
栀梦 2020-12-04 15:03

Given this extremely simple model:

public class MyContext : BaseContext
{
    public DbSet Foos { get; set; }
    public DbSet Bars { g         


        
8条回答
  •  星月不相逢
    2020-12-04 15:44

    Ok, here is the real answer =)

    First a little explanation

    if you have a property (like your Bar) noting a FK (ForeignKey), you can also have the corresponding FK field in your model so if we only need the FK and not the actual Bar we don't need it to go to the database:

    [ForeignKey("BarId")]
    public virtual Bar Bar { get; set; }
    public int BarId { get; set; }
    

    Now, to answer your question, what you can do to make the Bar as Required is to flag the BarId property as required, but not the Bar itself:

    [ForeignKey("BarId")]
    public virtual Bar Bar { get; set; }
    [Required] //this makes the trick
    public int BarId { get; set; }
    

    this works like a charm =)

提交回复
热议问题