Reputation: 8977
In my code -- names changed to protect the innocent :) -- I have:
[Table("schema.Items")] //The table
public class Item
{
//...all of the fields that exist in both the table and the view.
}
Clarifications:
ClassA
and ClassB
, both with the same properties, just so I can pull one from the view and the other from the table.Upvotes: 2
Views: 1935
Reputation: 14640
If I understand you correctly, you can use SqlQuery
to load from a query that is generated from view.
var db = ...; // instance of context
var q = db.Set<ViewModel>().Where(...).ToString();
var result = db.Database.SqlQuery<TableModel>(q);
PS
If the view name has a pattern like view_TableName
, you can just use TableModel
to generate the query then replace the table name with view name.
Here is an extension method that could achieve that.
public static string GetViewSql<T>(this DbContext db, IQueryable<T> q)
where T : class
{
const string prefix = "view_";
var tableName = Regex.Match(
db.Set<T>().ToString(),
@"FROM (\[.*\]\.\[.*\]) AS \[Extent1\]").Groups[1].Value;
var viewName = Regex.Replace(
tableName,
@"\[.*\]\.\[(.*)\]",
m => m.Groups[0].Value.Replace(
m.Groups[1].Value, prefix + m.Groups[1].Value));
var sql = q.ToString().Replace(tableName, viewName);
return sql;
}
Usage:
var query = db.Set<TableModel>().Where(...);
var sql = db.GetViewSql(query);
var result = db.Database.SqlQuery<TableModel>(sql);
Upvotes: 2