SeanKilleen
SeanKilleen

Reputation: 8977

Mapping a view and a table to the same model in EF?

My Scenario

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.
    }

Question

Clarifications:

Upvotes: 2

Views: 1935

Answers (1)

Yuliam Chandra
Yuliam Chandra

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

Related Questions