简体   繁体   English

实体框架实体完整性

[英]Entity Framework entity integrity

I want to validate each entity when saving. 我想在保存时验证每个实体。 That is, I have some custom C# function in each entity class that validates the data. 也就是说,我在每个实体类中都有一些自定义C#函数来验证数据。

How can I do that? 我怎样才能做到这一点? I don't want to use database constraints because they cannot express my constraints. 我不想使用数据库约束,因为它们无法表达我的约束。

Should I implement some interface??? 我应该实现一些接口???

The ObjectContext.SaveChanges method is virtual since EF 4.0. 从EF 4.0开始,ObjectContext.SaveChanges方法是虚拟的。 Overwrite this method and validate all entities there. 覆盖此方法并验证其中的所有实体。

http://msdn.microsoft.com/en-us/library/dd395500.aspx http://msdn.microsoft.com/en-us/library/dd395500.aspx

Iterate over all entities (not the deleted ones :)) in the context. 在上下文中迭代所有实体(不是已删除的:))。 Use the ObjectStateManager to gain access to the entities in the context. 使用ObjectStateManager可以访问上下文中的实体。

Hope this helps and best regards, 希望这有助于和最好的问候,

http://www.testmaster.ch/EntityFramework.test http://www.testmaster.ch/EntityFramework.test

Entity framework 3.5 and 4.0 offers even called SavingChanges . 实体框架3.5和4.0甚至提供了SavingChanges Entity framework 4.0 and 4.1 has SaveChanges method virtual (as already mentioned). 实体框架4.0和4.1具有虚拟的SaveChanges方法(如前所述)。

You can either override method or use event handler and write code like this for 3.5 and 4.0: 你可以覆盖方法或使用事件处理程序,并为3.5和4.0编写这样的代码:

var entities = context.ObjectStateManager
                      .GetObjectStateEntries(EntitiState.Modified | EntityState.Added)
                      .Where(e => !e.IsRelationship)
                      .Select(e => e.Entity)
                      .OfType<YourEntityType>();

foreach(var entity in entities)
{
    entity.Validate();
}

In DbContext API (EF 4.1) you must use 在DbContext API(EF 4.1)中,您必须使用

var entities = context.ChangeTracker
                      .Entries<YourEntityType>()
                      .Where(e.State == EntityState.Added || e.State == EntityState.Modified)
                      .Select(e => e.Entity);

foreach(var entity in entities)
{
    entity.Validate();
}

You can use custom interface implemented by your entities which will expose Validate method. 您可以使用实体实现的自定义接口,它将公开Validate方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM