I have an entity that is working great, but then I have a requirement to tack on an additional property that comes from another table. I don't have the ability to make a View, so I want to just add a field that is [NotMapped] then use the Context.Database.SqlQuery to execute my custom statement and return all the normal fields and this new field.
In other words something like this:
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
[NotMapped]
public string CustomerName { get; set; }
}
public List<Employee> GetEmployees()
{
using (MyContext context = new MyContext())
{
return context.Database.SqlQuery<Employee>("select E.EmployeeId, E.EmployeeName, C.CustomerName from Employee E left join Customer C on E.CustomerId = C.CustomerId").ToList();
}
}
Yes yes, not the best example, but the simplest way to get the point across. From everything I've been reading, SqlQuery is supposed to ignore attribute, so this should work, but my CustomerName is always coming back null (I've run the SQL in Management Studio, it has a value there, just not after EF deserializes into my objects).
What do I need to do to get this to work? Or can I? Was EF changed to not allow this?
-shnar
The NotMapped attribute is used to specify that an entity or property is not to be mapped to a table or column in the database.
The [NotMapped] attribute overrides this default convention. You can apply the [NotMapped] attribute on one or more properties for which you do NOT want to create a corresponding column in a database table. In the above example, the [NotMapped] attribute is applied to the Age property of the Student class.
I had the same trouble using stored procedures to do selects with calculated fields. I created a view model that looks exactly like my entity without the db annotations. Then after I call my stored procedure using the view model I select into my entity. So, using your example above:
public class EmployeeVM
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string CustomerName { get; set; }
}
Then you can call:
public List<Employee> GetEmployees()
{
using (MyContext context = new MyContext())
{
return context.Database.SqlQuery<EmployeeVM>("select E.EmployeeId, E.EmployeeName,
C.CustomerName from Employee E left join Customer C on E.CustomerId = C.CustomerId")
.Select(x=> new Employee(){
EmployeeId = x.EmployeeId,
EmployeeName = x.EmployeeName,
CustomerName = x.CustomerName
}).ToList();
}
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With