Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 403
mehanik Avatar asked Jan 19 '12 12:01

mehanik


1 Answers

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.

like image 76
Ladislav Mrnka Avatar answered Oct 27 '22 00:10

Ladislav Mrnka