c# - Entity Framework Code First - 两个名称相同但 namespace 不同的实体

标签 c# entity-framework entity-framework-4.1 code-first

我在以下情况下遇到数据库生成问题:

1.cs First.Entities 命名空间中的项目实体映射到 First_Project 表。

namespace First.Entities
{
    #region using section

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity.ModelConfiguration;
    using System.Diagnostics.CodeAnalysis;

    #endregion

    [Table("First_Project")]
    public class Project
    {
        [Key]
        public int Id
        {
            get;
            set;
        }

        [Required]
        [MaxLength(1000)]
        public string Name
        {
            get;
            set;
        }
    }
}

2.cs Second.Entities 命名空间中的项目实体映射到 Second_Project 表。

namespace Second.Entities
{
    #region using section

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity.ModelConfiguration;
    using System.Diagnostics.CodeAnalysis;

    #endregion

    [Table("Second_Project")]
    public class Project
    {
        [Key]
        public int Id
        {
            get;
            set;
        }

        [Required]
        [MaxLength(1000)]
        public string Name
        {
            get;
            set;
        }
    }
}

3.cs DbContext文件

namespace DataContext
{
    #region using section

    using System.Collections.Generic;
    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.ModelConfiguration.Conventions;
    using System.Diagnostics.CodeAnalysis;
    using First.Entities;
    using Second.Entities;

    #endregion

    public class MyEntities : DbContext
    {
        public DbSet<First.Entities.Project> FirstProjects { get; set; }

        public DbSet<Second.Entities.Project> SecondProjects { get; set; }
    }
}

请帮忙。

最佳答案

这是不可能的。单个上下文类型中每个映射实体的类名(无命名空间)必须是唯一的。 this answer 中概述了原因.

您必须使用不同的类名。顺便提一句。使用不同的(更具体的)类名还可以使您的代码更具可读性,并且您的类型更易于使用。

关于c# - Entity Framework Code First - 两个名称相同但 namespace 不同的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8926322/

相关文章:

c# - EF - 在 HTTP 请求期间创建模型异常时无法使用上下文

c# - 这不应该工作吗? (类型转换/拆箱)

c# - Azure 搜索索引器清除文档

entity-framework - EF 4.3.1 与 VS 2011

c# - 在另一个表达式中使用保存的表达式

c# - 什么时候应该使用导航属性来查询数据库?

c# - EF 4.1 使用自定义类型处理资金

c# - Entity Framework 4.1 中的性能监控选项

c# - 是否可以通过生成 .proto 文件使用 python 反序列化在 c# 中使用 protobuf-net 序列化的对象?

c# - 来自引用的 .NET Standard 项目的多个 DLL