Skip to content

Support separation of query and update mapping #15671

@bdebaere

Description

@bdebaere

Copied from my StackOverflow post.

Consider the model below. I have an Order class and an OrderLine class. The Order.TotalAmount is calculated through a view which performs an OUTER APPLY across all the Order.OrderLines.

    [Table("SelectOrder")]
    public class Order
    {
    	public decimal TotalAmount { get; set; }
    	
    	public virtual ICollection<OrderLine> OrderLines { get; set; }
    }
    
    [Table("SelectOrderLine")]
    public class OrderLine
    {
    	public decimal Amount { get; set; }
    	
    	public virtual Order Order { get; set; }
    }

I have decorated my classes with the TableAttribute to enable Entity Framework Core to get the data from the views to the entity. The TableAttribute actually points to the view instead.

Now I would like to perform inserts, updates and deletes. This poses a problem as it's not possible to use a view with an OUTER APPLY for these changes. I've tried using query types for this but you cannot define an entity as both a query type and an entity type. Doing so results in an error for me. So adding a TableAttribute with the actual table e.g. Order in combination with modelBuilder.Query<Order>().ToView("SelectOrder"); does not work.

I could create a separate class SelectOrder which is mapped to the view and map my Order entity to the table. Or I could build a custom attribute and perform some custom SQL generation by overriding the SqlServerQuerySqlGenerator.

But before I go down these roads... Is it really not possible to map an entity to both a view for selects and a table for inserts, updates and deletes?

I've since gone through the code and noticed that SqlServerQuerySqlGenerator is not used to generate non-SELECT queries, am I correct? So I'm left with adjusting the code to a custom EF Core version and add a ViewAttribute which it uses during INSERT INTO SELECT ... FROM generation or multiple classes which is the least preferred option by the person pulling my strings. Is there nothing better?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions