asp.net-mvc-3 - 如何为由Data-First自动创建的实体添加数据注释?

标签 asp.net-mvc-3 entity-framework entity-framework-4 database-first

如果是模型优先的,则我们使用[MetadataType(typeof(ConceptMetadataSource))]附加一个MetadataSource文件,该文件包含所有数据注释,例如[HiddenInput(DisplayValue = false)][Display(Name = "Title")]

例如:

[MetadataType(typeof(ConceptMetadataSource))]
public partial class Concept
...

现在,由于存在现有数据库,因此我使用数据库优先方法。这次,实体类由edmx模型自动创建。在每个实体类的开头,下面都有注释行:
//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

由于一旦我们修改了数据库中的表,代码将被重新生成,因此每次实体类被重新生成时,数据注释都将被清除。

谁能告诉我注释这些实体类的最佳方法是什么?谢谢你。

最佳答案

您要做的就是创建另一个局部类并使用metadatatype属性。这是示例代码

//This is generated by EDMX

namespace DataLayer
{
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
        public Customer()
        {
            this.CustomerAddresses = new HashSet<CustomerAddress>();
            this.CustomerOrders = new HashSet<CustomerOrder>();
        }

        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailId { get; set; }


        public Nullable<System.DateTime> DateOfBirth { get; set; }

        public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; }
        public virtual ICollection<CustomerOrder> CustomerOrders { get; set; }
    }
}

手动添加以下代码
namespace DataLayer
{
    [MetadataType(typeof(CustomerMetaData))]
    public partial  class Customer
    {

    }
    public class CustomerMetaData
    {
        [StringLength(10, ErrorMessage = "First name must be 25 characters or less in length.")]
        [Required(ErrorMessage = "First name is required.")]
        public String FirstName { get; set; }
    }
}

关于asp.net-mvc-3 - 如何为由Data-First自动创建的实体添加数据注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932193/

相关文章:

asp.net-mvc-3 - 在运行时更改 View 模型的 MetadataType 属性

c# - 数据注释如何工作?

.net - 使用FileStreamResult,如何关闭MemoryStream?

c# - 进行多次更新时如何避免在 Entity Framework 4 中锁定数据库

asp.net-mvc - 添加多对多关系,无需从数据库中获取子实体

asp.net - HtmlHelper.EditorFor与Html.TextBox与Html输入

entity-framework - WillCascadeOnDelete 不会在数据库上建立级联删除

c# - Code First 外键 - 多重性在角色中无效

c# - 如何快速加载相关实体

c# - WCF关系