Asp.net mvc 3 实体框架数据库优先使用数据命名

Asp.net mvc 3 实体框架数据库优先使用数据命名,asp.net-mvc-3,entity-framework-5,data-annotations,Asp.net Mvc 3,Entity Framework 5,Data Annotations,我有一个项目采用了EF和代码优先的方法,数据注释的使用非常简单。现在我首先使用数据库,我发现使用数据注释更为具体,所以我想知道实现它的正确步骤 我提供数据访问的项目结构如下: 在modeltextensions中,我创建了所有文件,用于将数据注释添加到DbContextModel.tt实体中 以下是我在modeldextensions中的一个文件的结构: using System; using System.ComponentModel.DataAnnotations; using Syste

我有一个项目采用了
EF
和代码优先的方法,数据注释的使用非常简单。现在我首先使用数据库,我发现使用数据注释更为具体,所以我想知道实现它的正确步骤

我提供数据访问的项目结构如下:

modeltextensions
中,我创建了所有文件,用于将数据注释添加到
DbContextModel.tt
实体中

以下是我在
modeldextensions
中的一个文件的结构:

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; }
    }
}
我这里有几个问题。首先是名称空间。它应该是这样的
名称空间DataAccess.ModelExtensions
,或者我必须删除
.ModelExtensions
部分。我先看一个使用DB的项目,那里的名称空间只是
DataAccess
不确定为什么需要它(如果需要的话)。另外-是否需要向
DbContextModel.tt
实体添加一些其他引用?现在我使用标准的C类来实现这一点,然后将它们重命名为:
公共部分类MCS\u ContentTypes:BaseEntity
。我是否必须使用特殊的方法来创建实体以显式公开实体与此文件之间的连接?

1)扩展模型的命名空间必须与EF自动生成的实体类的命名空间相同-如果
DbContextModel.tt
实体类的命名空间为
DataAccess
,您应该将类的名称空间设置为
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
继承。

部分类文件应该保存在哪里?我认为将其添加到
DbContextModel.tt
是个坏主意。@CodeswithHammer保存它们的位置并不重要。您只需要在同一名称空间中创建它们。再看一次代码示例,更准确地说,我想我明白了。我在带有属性的类中重用
名称空间MySolution