1

I have one project with EF and Code First approach and there using of Data Annotations was straight forward. Now I'm working with Database First and I see that using Data Annotations is more specific so I want to know the right steps to implement it.

The structure of my project that provides Data Access is this:

DataAccess

In ModelExtensions are all my files that I've created to add the Data Annotations to the DbContextModel.tt entities.

Here is the structure of one of my files in ModelExtensions:

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace DataAccess.ModelExtensions
{
    [MetadataType(typeof(MCS_ContentTypesMetaData))]
    public partial class MCS_ContentTypes : BaseEntity
    {

    }

    internal sealed class MCS_ContentTypesMetaData
    {
        [Required]
        [StringLength(10)]
        public string Name { get; set; }
    }
}

I have several questions here. First - the namespace. Should it be like this namespace DataAccess.ModelExtensions or I have to remove the .ModelExtensions part. I was looking at a project using DB first and there the namespace was just DataAccess not sure why it is needed (if so). Also - Do I need to add some other references to the DbContextModel.tt entities? Now I use standard C# classes for this and then rename them to : public partial class MCS_ContentTypes : BaseEntity. Do I have to use a special approach for creating those to explicitly expose the connection between the entity and this file?

4

1 回答 1

2

1) 扩展模型的命名空间必须与 EF 自动生成的实体类的命名空间相同 - 如果实体类的命名空间DbContextModel.ttDataAccess,则应将类的命名空间设置为DataAccess

2)我没有完全理解您的问题,但是在这种方法中,实体类的名称和您的类必须相同。

以下示例显示了它应该是什么。假设 EF 为您生成以下实体类:

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

    public partial class News
    {
        public int ID { get; set; }
        public string Title { get; set; }        
    }
}

因此,您的部分类应如下所示:

namespace YourSolution
{
    [MetadataType(typeof(NewsAttribs))]
    public partial class News
    {
        // leave it empty.
    }

    public class NewsAttribs
    {            
        // Your attribs will come here.

        [Display(Name = "News title")]
        [Required(ErrorMessage = "Please enter the news title.")]
        public string Title { get; set; }

        // and other properties you want...
    }
}

所以,你不需要任何: BaseEntity继承。

于 2013-07-26T02:10:32.010 回答