mehanik
mehanik

Reputation: 1067

Entity Framework Code First - two entities with same name but in different namespaces

I have a problem with db generation in following scenario:

1.cs Project entity in First.Entities namespace maped to First_Project table.

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 Project entity in Second.Entities namespace maped to Second_Project table.

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 file

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

Please help.

Upvotes: 11

Views: 7927

Answers (2)

BaNSHee
BaNSHee

Reputation: 1

I think it is possible, when you use a different database schema for both entities.

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

Upvotes: -1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

It is not possible. Class name (without namespace) for every mapped entity in single context type must be unique. The reason is outlined in this answer.

You must use different class names. Btw. using different (more specific) class names also makes your code better readable and your types better usable.

Upvotes: 11

Related Questions