Search code examples
c#model-view-controllerdata-bindingmodelmodel-binding

.NET Core MVC - How to populate model properties using query


I am having trouble figuring out how I can populate an MVC model by using something like a query or linq statement. I have my database structured to where all model properties are stored in an attribute value table. An Attribute table stores all possible attributes. A linking table joins Attribute to the Entity that has that attribute via FK relationships. This is done so that the data that I store is easily extensible without having to change the database structure by adding new columns and tables as I gather more data.

The problem that I am having is that I can't figure out how to populate a model with the values stored in my attribute value table for a given model. For example, say I have a Car model having Make (attributeId 1), Model (attributeId2), and Year (attributeId:3) attributes stored in the Attribute table. The AttributeValue table stores the values (in columns, like a normal table, the first column name is AttributeId, the second Column name is AttributeValue. I'm using a colon to separate them in the example) AttributeId 1 : Toyota, AttributeId 2: Camry, AttributeId 3: 2020.

How can I create a model binding or something similar to populate my Car model by doing something like: Car.Make = SELECT Value FROM AttributeValue WHERE AttributeId = 1; Car.Model = SELECT Value FROM AttributeValue WHERE AttributeId = 2, etc

I am fairly new to MVC, so forgive me if I'm missing something simple.

Thanks!


Solution

  • If I understood your question correctly, I believe you need to apply Auto Mapper. Refer the following link.

    Auto Mapper Reference

    And for the query part, you can achieve that using LINQ.

    Select Statement Using LINQ in C#