Home > Software design >  I can't show the category name instead of the ID
I can't show the category name instead of the ID

Time:07-26

I have some entities, Products, and Categories. I need to call the category name instead of the category ID. When I try to call the name, I get this error:

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
sistemaFacturacion.Components.Products.ListProductComponent.BuildRenderTree(RenderTreeBuilder __builder) in ListProductComponent.razor, line 22

This is the code I use to call the category name.

<table > 
    <thead>
        <tr>
            <th>Id</th>
            <th>Nombre</th>
            <th>Cantidad</th>
            <th>Categoria</th>
            <th>Accion</th>
        </tr>
    </thead>

    <tbody>
        @foreach (var product in tempProducts)
        {
            <tr>
                <td>@product.ProductId</td>
                <td>@product.Name</td>
                <td>@product.Units</td>
                <td>@product.Category.Name</td> //HERE IS THE ERROR LINE

                <td>
                    <a type="button" 
                     
                    href="">Editar</a>
                </td>
            </tr>
        }
    </tbody>
</table>

@code {
    List<ProductsEntity> products = new List<ProductsEntity>();
    List<ProductsEntity> tempProducts = new List<ProductsEntity>();
    List<CategoriesEntity> Category = new List<CategoriesEntity>();

    protected override async Task OnInitializedAsync()
    {
        products = B_Product.ProductList();
        tempProducts = products;
        Category = B_Category.CategoryList();
    }

}

These are the entities:

 namespace EntitiesApp
{
    public class CategoriesEntity
    {
        [Key]
        public int CategoryId { get; set; }

        [Required]
        [MaxLength(20)]
        public string Name { get; set; }

        //Relation with Products
        public ICollection<ProductsEntity> Products { get; set; } // 1 to N
    }
}

This is the users entity

namespace EntitiesApp
{
    public class ProductsEntity
    {
        [Key]
        public int ProductId { get; set; }

        [Required]
        [MaxLength(100)]
        public string Name { get; set; }

        [Required]
        public int Units { get; set; }

        [Required]
        public float Price { get; set; }

        public Nullable <float> Cost { get; set; }

        
        [MaxLength(100)]
        public string SKU { get; set; }

        //Relation with Categories - Relation 1 to 1
        public int CategoryId { get; set; }
        public CategoriesEntity Category { get; set; }

    }
}

I'm not sure what's the issue... Thanks for your time :)

CodePudding user response:

You got 'NullReferenceException' therefore you probably forgot to perform the load data operation in EF. If you want to use any Navigation Property like 'Category' in your code you need to load related data.

You have to make sure you have loaded Category for the ProductsEntity. You can't directly use it by default. If you want to use it without loading, you can use 'Lazy Loading' but this isn't default approach of EF. On the other hand, 'Eager Loading' method is suitable in general. Look at this => https://docs.microsoft.com/en-us/ef/core/querying/related-data/

By the way, I can give you some tips to quick fix. In your code, There is 'B_Product' but it's unclear where this came from as I can't see the full code. Assume that you can reach all your DbSets like 'ProductsEntity' and 'CategoriesEntity' in _context. In addition instead of 'ProductsEntity', you can simply call it 'Product'. This way it will be shorter and more concise.

Assume that this is your Context class and these are your DbSets

 public DbSet<Product> Products { get; set; }
 public DbSet<Category> Categories { get; set; }

After performing the operation below, you will be able to access the 'category' Navigation Property over a 'Product' Model.

 private readonly DbContext _context;
_context.Products.Include(p => p.Category).ToList();

On the other hand, I assumed you were using Entity Framework. But maybe you didn't use database and you get the data through a collection. In this case, the logic would still be the same. Before using 'category' over Product Model in your .cshtml file, you must load the relevant data into it.

  • Related