Search code examples
c#asp.net.netentity-framework-core

Class conflict with same table name annotation in entity framework


I'm developing an ASP NET application, but I'm having a problem with the Entity Framework.

In my application I use 2 different databases at the same time, the problem comes when both databases have the same table name.

Example:

sample code image

In this image, we have 2 classes, both with the same name in the annotation and with the same primary key, the difference is the rest of the structure that is different from one to the other. The first class refers to 1 database and the other to the other database.

declaration

When I have to make a request the entity framework returns an error.

Cannot use table 'TBL_EMPRESAS' for entity type 'EmpresaDomain' since it is being used for entity type 'EmpresaAuthenticationDomain' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'EmpresaDomain' on the primary key properties and pointing to the primary key on another entity type mapped to 'TBL_EMPRESAS'.


Solution

  • You've added them to the same Context this will cause EF to think that they are actually the same type, which they are not.

    You should create a separate Context class per database and only add the DbSet in the Context class in which it belongs.

    Like this (if left out everything else for readability's sake):

    public class MyContext : DbContext {
    
         public DbSet<EmpresaDomain> Empresas { get; set; }
    
    }
    
    public class MyOtherContext : DbContext {
    
        public DbSet<EmpresaAuthenticationDomain> EmpresesAuthentications { get; set; }
    
    }
    
    
    

    Hope this helps!