向实体框架(或Linq To SQL)生成的类添加数据注释

本文关键字:添加 注释 数据 SQL 框架 实体 To Linq | 更新日期: 2023-09-27 18:13:14

是否可以添加更多的Data Anootation成员,如Range, Required,…到Entity FrameworkLinq to SQL自动生成类?

我想对我的类使用数据注释验证

感谢

重要:与本主题相关:使用元数据与实体框架来验证使用数据注释

编辑1)

为Northwind数据库创建实体框架模型,并添加Product类。部分代码是这样的:

[EdmEntityTypeAttribute(NamespaceName="NorthwindModel", Name="Product")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Product : EntityObject
{
    #region Factory Method
    /// <summary>
    /// Create a new Product object.
    /// </summary>
    /// <param name="productID">Initial value of the ProductID property.</param>
    /// <param name="productName">Initial value of the ProductName property.</param>
    /// <param name="discontinued">Initial value of the Discontinued property.</param>
    public static Product CreateProduct(global::System.Int32 productID, global::System.String productName, global::System.Boolean discontinued)
    {
        Product product = new Product();
        product.ProductID = productID;
        product.ProductName = productName;
        product.Discontinued = discontinued;
        return product;
    }
    #endregion
    #region Primitive Properties
    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int32 ProductID
    {
        get
        {
            return _ProductID;
        }
        set
        {
            if (_ProductID != value)
            {
                OnProductIDChanging(value);
                ReportPropertyChanging("ProductID");
                _ProductID = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("ProductID");
                OnProductIDChanged();
            }
        }
    }
    private global::System.Int32 _ProductID;
    partial void OnProductIDChanging(global::System.Int32 value);
    partial void OnProductIDChanged();

我想要ProductID是必需的,但我不能这样写代码:

public partial class Product 
    {
        [Required(ErrorMessage="nima")]
        public global::System.Int32 ProductID;
    }

向实体框架(或Linq To SQL)生成的类添加数据注释

是。您需要为每个实体创建第二个部分类,并将其链接到具有替代属性的辅助类。

假设您有一个生成的partial class Customer { public string Name { get; set; } }
生成的类总是被标记为部分类。

你需要添加一个文件:

[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
    // it's possible to add logic and non-mapped properties here
}

public class CustomerMetadata
{
    [Required(ErrorMessage="Name is required")] 
    public object Name { get; set; }   // note the 'object' type, can be anything
}

我个人认为这不是一个非常优雅的解决方案,但它是有效的。