locked
Asp mvc 5 Binding model RRS feed

  • Question

  • User1676873935 posted

    Hi,

    I have this model : 

      public class ProductModel
        {
            public virtual int ProductModelId { get; set; }
            public string ProductIdid { get; set; }
            public List<BarcodesModel> ProductBarcodes { get; set; }
            public CategoriesModel ProductCategory { get; set; }
    	public InternationalizationModel ProductInternationalization { get; set; }
            public List<ImagesModel> ProductImages { get; set; }
    	public StockModel ProductStock { get; set; }
        }

    But when I would like to get it with this way : 

    List<ProductModel> test = db.ProductModels.ToList();

    All of this is null : ProductBarcodes,  ProductCategory, ProductInternationalization ,ProductImages ,ProductStock .

    I don't know why....

    Can you help me?

    thanks

    Friday, November 9, 2018 4:07 PM

All replies

  • User1676873935 posted

    Ok... I understand... If I want to get it, I have to write this 

    public virtual List<ImagesModel> ProductImages { get; set; }


    Friday, November 9, 2018 4:13 PM
  • User1520731567 posted

    Hi Waldpest,

    Usually virtual properties are being used by Entity Framework for the lazy loading of related objects (process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed).

    Lazy loading is delaying the loading of related data, until you specifically request for it.

    More details,you could refer to:

    http://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx

    https://blogs.msdn.microsoft.com/adonet/2011/01/31/using-dbcontext-in-ef-4-1-part-6-loading-related-entities/

    Best Regards.

    Yuki Tao

    Monday, November 12, 2018 9:17 AM
  • User-821857111 posted

    All of this is null : ProductBarcodes,  ProductCategory, ProductInternationalization ,ProductImages ,ProductStock .
    They are null because that is the default value for those types if you haven't instantiated them. You can instantiate collections by using an expression:

    public class ProductModel
    {
        public virtual int ProductModelId { get; set; }
        public string ProductIdid { get; set; }
        public List<BarcodesModel> ProductBarcodes { get; set; } = new List<BarcodesModel>();
        public CategoriesModel ProductCategory { get; set; }
        public InternationalizationModel ProductInternationalization { get; set; }
        public List<ImagesModel> ProductImages { get; set; } = new List<List<ImagesModel>();
        public StockModel ProductStock { get; set; }
    }

    Now you can use Any() to test your collections:

    if(ProductImages.Any())
    {
        ....

    But you still need to test for null for your other properties.

    Monday, November 12, 2018 10:23 AM