避免在Entity Framework中明确标记未修改的属性

时间:2015-02-07 15:57:57

标签: c# asp.net entity-framework

每当我更新实体时,我都需要将表单中的每个字段都包含为隐藏输入,这样它的值就不会设置为null

将属性设置为未修改,如下面的代码,可以防止这种情况发生。但是这段代码被抽象为由IRepository类封装的通用UnitOfWork接口,因此我不能为每个实体指定未修改的属性。

Entry(entry.Entity as MyModel).Property(e => e.AProperty).IsModified = false;

还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用MVVM架构模式。模型视图ViewModel(MVVM)是一种用于软件工程的架构模式,源自Microsoft,作为Martin Fowler引入的Presentation Model设计模式的专业化。

Model : Model refers to your application data. In a real world ASP.NET web application, your data will typically be stored in a SQL Server database and your UI gets it from the server by making AJAX requests or some similar technique.
View Model : View Model refers to your data and UI level operations that you wish to perform on the data. The operations may include business validations or conditional checks or updating certain parts of the web page. You can think of View Model as a wrapper over your model data that adds UI level operations to it.
View : View is the user interface of your application. A View interacts with View Model to invoke some operations. A View is updated whenever data from the View Model changes. For a web application a view typically takes the form of an HTML document.

这是使用ASP.NET和EF的真实示例。 http://blog.tonysneed.com/2014/05/28/real-world-mvvm-with-entity-framework-and-asp-net-web-api/