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();
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();