entity-framework-4 - 如何确定哪个实体在 SaveChanges 上失败

标签 entity-framework-4

当我调用 SaveChanges 时,我的对象上下文中有许多未决的更改。某处有一个实体,其列的值太长。这会导致 SqlException:字符串或二进制数据将被截断。

问题是如何确定违规实体/列?

最佳答案

您可以考虑使用 DataAnnotations并构建您的好友类以进行验证。然后,如果他们的数据不正确,您会向用户显示友好的验证错误。

Imports System.ComponentModel.DataAnnotations 

Namespace Domain 
#Region "Validation" 

<MetadataType(GetType(UserMetaData))> _ 
Partial Public Class User 
End Class 


''' <summary> 
''' Validation for all User data. 
''' </summary> 
''' <remarks>All validation is done at the Service Layer</remarks> 
Public Class UserMetaData 

    <DisplayName("name")> _ 
    <Required(ErrorMessage:="Username is required.")> _ 
    <StringLength(30, ErrorMessage:="Username cannot exceed 30 characters.")> _ 
    <RegularExpression("^\w{3,30}$", ErrorMessage:="Not a valid username.")> _ 
    Public Property UserName As String 

    <DisplayName("email")> _ 
    <StringLength(50, ErrorMessage:="Email Address cannot exceed 50 characters.")> _ 
    <RegularExpression("^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$", ErrorMessage:="Not a valid email address.")> _ 
    Public Property Email As String 

    <DisplayName("website")> _ 
    <StringLength(256, ErrorMessage:="Web Address cannot exceed 256 characters.")> _ 
    <RegularExpression("^http(s?)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$", ErrorMessage:="Not a valid website address.")> _ 
    Public Property WebSite As String 

    <DisplayName("about")> _ 
    <StringLength(2000, ErrorMessage:="Profile cannot exceed 2000 characters.")> _ 
    Public Property About As String 

    <DisplayName("region")> _ 
    <Required(ErrorMessage:="Region is required.")> _ 
    Public Property UserRegion As Integer 

    <DisplayName("birthdate")> _ 
    <DisplayFormat(ApplyFormatInEditMode:=True, ConvertEmptyStringToNull:=True, DataFormatString:="{0:MM/dd/yyyy}")> _ 
    Public Property BirthDate As DateTime 

End Class 
#End Region 
End Namespace

更多引用

http://adventuresdotnet.blogspot.com/2009/08/aspnet-webforms-validation-with-data.html
http://blogs.msdn.com/b/jimoneil/archive/2008/07/08/dynamic-data-annotations.aspx
http://www.ipreferjim.com/site/2010/05/system-componentmodel-dataannotations-for-asp-net-web-forms/

关于entity-framework-4 - 如何确定哪个实体在 SaveChanges 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3471785/

相关文章:

asp.net-mvc - 使用 IRepository 进行 Entity Framework 测试 - 延迟加载问题

entity-framework - 无法使用 Entity Framework 4.3.1 在实体类型上设置字段/属性

c# - 获取实体的属性列表

c# - EF Code First 如何为派生类创建单独的表?

silverlight-4.0 - 绑定(bind)到 EntityCollection : Silverlight 4 中第一项的属性

c# - LINQ 到实体 : All method not yielding the expected result

c# - HasOptional 对应的 DataAnnotation 属性

c# - Entity Framework POCO - 更新集合

c# - 通过使用 linq to ado.net 实体 froamwork 将记录插入具有一对多关系的两个表中

c# - 是否可以在 SqlConnection 中使用 EF4 EntityConnection?