9

如果模型优先,我们使用[MetadataType(typeof(ConceptMetadataSource))]附加一个 MetadataSource 文件,其中包含所有数据注释,如 [HiddenInput(DisplayValue = false)]or [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>
//------------------------------------------------------------------------------

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

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

4

3 回答 3

13

您所要做的就是创建另一个部分类并使用 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; }
    }
}
于 2013-02-06T15:55:31.737 回答
6

好的,这就是答案。

诀窍是,自动生成的类都是部分类。编译过程将合并所有具有相同名称的部分类。

如果我们已经public partial class Concept生成了DbContext,我们需要做的就是创建另一个以 开头的public partial class Concept。这个新的分部类可以在不同的文件夹中创建,但我们需要将其命名空间更新为与自动生成的分部类相同。

在这个新创建的部分类中,我们可以添加各种数据注释,例如

[Required(ErrorMesssage="This Field is required")]

或者,我们甚至可以添加新的属性,例如

FullName {get {return string.Format("{0} {1}", FirstName, LastName);}}

如果再次从数据库更新模型,则只会更新自动生成的部分类。那些新手动添加的包含我们的注释和其他操作的部分类将保持不变。

于 2012-05-07T15:47:43.213 回答
0

定义一个视图模型

public class VMConcept
{ 
    public Concept NewConcept {get; set;}
}

[MetadataType(typeof(ConceptMetadataSource))]
public partial class Concept{}

public class ConceptMetadataSource {

 [Required(ErrorMesssage="This Field is required")]
 public string PropertyName {get; set;}
}
于 2012-01-19T19:48:47.330 回答