Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6 is not mapping my columns correctly using Attributes

I am using EF6 to query data from a database. The database existed before the code and belongs to another application, so I cannot modify the database at all. I believe I am using a code first approach, even though the database already exists(Forgive me as I'm new to EF). The issue is that I am not able to pull back data for a column that is setup as follows;

[Column("ITEM_QTY")]
public decimal ItemQuantity { get; set; }

Now if I rename the property to ITEM_QTY, it pulls the data correctly. I'm not sure what I'm missing. I can pull data from any other field correctly, but this field returns 0 regardless of whats in the DB. Can anyone provide any direction?

In another discussion, someone had suggested a possible issue with the underscores in the column name. Not sure if that could be it, but adding for info. Thanks.

Edit: Adding code used to query database. Note that this was setup before I started working on the project, so following same convention;

var t = this.Database.SqlQuery<InventoryDb>("select top 100 * from COMPANY_INVENTORY with (NOLOCK) where COMPANY = @CompanyName",
                new SqlParameter("CompanyName", companyName)).ToList();
like image 240
Brian Morrison Avatar asked Dec 19 '25 15:12

Brian Morrison


1 Answers

Your Column attribute will be ignored if you are using custom SqlQuery<T> on the DbContext. You need to pass the Sql statement with the alias for the property name that matches your entity.

var t = this.Database.SqlQuery<InventoryDb>("select top 100 Item_QTY as [ItemQuantity], ... other columns ... from COMPANY_INVENTORY with (NOLOCK) where COMPANY = @CompanyName",
            new SqlParameter("CompanyName", companyName)).ToList();

EDIT: Was checking this further out of curiosity and it appears that EF should respect the Column attribute if you used the DbSet.SqlQuery instead. I have not tried this though. (https://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=vs.113).aspx)

var t = this.Inventory.SqlQuery("select top 100 * from COMPANY_INVENTORY with (NOLOCK) where COMPANY = @CompanyName",
            new SqlParameter("CompanyName", companyName)).ToList();
like image 185
Vidmantas Blazevicius Avatar answered Dec 22 '25 04:12

Vidmantas Blazevicius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!