将更改保存到映射到视图的实体

Saving change to an Entity which is mapped to a View

我可以使用 Entity Framework 来保存对视图的更改吗?

我有一个映射到视图的实体。

[Table("MyView")]
public class MyEntity
{
    public long MyEntityId { get; set; }

    public string Name { get; set; }
}

View本身是这样的:

CREATE VIEW MyView AS 
SELECT 
    t.MyEntityId,
    t.Name,
FROM 
    MyTable t

我可以使用 Entity Framework 更改跟踪来保存对此视图的更改吗?那么这样的事情可能吗:

var record = Context.MyEntity.Where(e => e.MyEntityId == 150).FirstOrDefault();
record.Name = "New Name";
Context.SaveChanges();

看起来 Entity Framework 不关心实体是否映射到视图或 Table...它只会创建相同的更新脚本。对于上面的示例,EF 生成以下脚本:

UPDATE [MyView] SET [Name]=@gp1 WHERE [MyEntityId] = 150
-- @gp1: 'New Name' (Type = String, IsNullable = false, Size = 8)

因此 EF 不会引入任何更新视图的额外限制...但是我们仍然有更新视图的 RDBMS 特定限制...例如,在 SQL 服务器中,视图可以是已更新 subject to the following limitations

  • If the view contains joins between multiple tables, you can only insert and update one table in the view, and you can't delete rows.

  • You can't directly modify data in views based on union queries. You can't modify data in views that use GROUP BY or DISTINCT statements.

  • All columns being modified are subject to the same restrictions as if the statements were being executed directly against the base table.

  • Text and image columns can't be modified through views.

  • There is no checking of view criteria. For example, if the view selects all customers who live in Paris, and data is modified to
    either add or edit a row that does not have City = 'Paris', the data
    will be modified in the base table but not shown in the view, unless
    WITH CHECK OPTION is used when defining the view.