开发者

EF CF: is it right always is null the object of FK?

开发者 https://www.devze.com 2023-04-09 05:13 出处:网络
I have a Domain Models like this public class ShipToCode { public int ShipToCodeID { get; set; } [Required(ErrorMessage = \"Nombre es requerido\",AllowEmptyStrings = false)]

I have a Domain Models like this

public class ShipToCode
    {

        public int ShipToCodeID { get; set; }

        [Required(ErrorMessage = "Nombre es requerido",AllowEmptyStrings = false)]
        [StringLength(50, ErrorMessage = "Debe ser menor a 50 carácteres")]
        [MaxLength(50)]
        [Column("nb_name")]
        public string Name { get; set; }

        [StringLength(15, ErrorMessage = "Debe ser menor a 15 carácteres")]
        [MaxLength(15)]
        [Column("cd_locId")]
        public string locId { get; set; }

        public int? RegionID { get; set; }
        public virtual Region Region { get; set; }


        [Required(ErrorMessage = "Dealer es requerido")]
        public int DealerID { get; set; }
        public virtual Dealer Dealer { get; set; }
    }
public class Dealer
    {

        public Dealer()

        {

            this.ShipToCode = new HashSet<ShipToCode>();
        }

        public int DealerID { get; set; }

        [Required(ErrorMessage = "Nombre es requerido")]
        [StringLength(100, ErrorMessage = "Debe ser menor a 100 carácteres")]
        [MaxLength(100)]
        [Column("nb_name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Codigo de distribuidor es requerido")]
        [StringLength(100, ErrorMessage = "Debe ser menor a 100 carácteres")]
        [MaxLength(100)]
        [Column("cd_dealerCode")]
        public string DealerCode { get; set; }

        public virtual ICollection<开发者_高级运维;ShipToCode> ShipToCode { get; private set; }


    }

In my context

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            modelBuilder.Entity<ShipToCode>()
               .HasRequired<Dealer>(d => d.Dealer)
               .WithMany(d => d.ShipToCode)
               .HasForeignKey<int>(c => c.DealerID);

        }

But when i get any ShipToCode or Dealer, using the function of find of the DbSet, my object of Dealer in the ShipToCode or The ICollection of ShipToCode in Dealer is empty

This is normal or i'm missing something?? please help!!


In your Dealer the property,
public virtual ICollection<ShipToCode> ShipToCode { get; private set; }
has the private set method you need to make it public otherwise EF can't set it from the database. And make sure you have enabled lazyloading in your context. If you are not enabled lazy loading you can use eager loading like this,

Context.ShipToCodes.Include(s=>s.Dealer ).where(s=>s.ShipToCodeID ==1)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号