【问题标题】:Entity Framework Code First - two entities with same name but in different namespaces实体框架代码优先 - 两个具有相同名称但在不同命名空间中的实体
【发布时间】:2012-02-14 03:04:10
【问题描述】:

我在以下场景中遇到了数据库生成问题:

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

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_Project 表的 Second.Entities 命名空间中的项目实体。

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; }
    }
}

请帮忙。

【问题讨论】:

  • 您遇到什么错误?您需要什么帮助?
  • 在这种情况下无法创建数据库。错误是:
  • “Second.Entities.Project”类型未映射。使用 Ignore 方法或 NotMappedAttribute 数据注释检查该类型是否被显式排除。验证该类型是否被定义为一个类,不是原始的、嵌套的或泛型的,并且不是从 EntityObject 继承的。
  • 如何修复我的场景。我不想重命名项目类别。我想有 2 个项目类,但在不同的命名空间中。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我认为这是可能的,当您为两个实体使用不同的数据库架构时。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<First.Entities.Project>().ToTable("Project", "First");
         modelBuilder.Entity<Second.Entities.Project>().ToTable("Project", "Second");
    }
    

    【讨论】:

    • “我认为”——请自信地发布答案,您知道您在说什么。你真的亲自尝试过吗?如果没有,请这样做。
    • 我使用的是 EF 6.1.3,这是不可能的。 EF 抛出运行时错误。
    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多