简体   繁体   中英

EF Core relation without foreign key

Currently I have a problem, I work with a linear database, that is, it does not have foreign keys, the tables are related only by the id field and you have to make a query in the database to join tables with joins and get results, in the mysql database it works well because they are only queries, but with Entity Framework is where the problem arises, I have an employee table and a person table and they are related by the PersonId so with a linq c# query, I want to obtain a list of employees with information also of the person so I would do something like this:

var empleados = context.Empleados.Include(x => x.Personas).ToList();

but since they are not related at the database level with a foreign key, EF does not allow me to use include.

then try something like this:

  var queryable = from e in context.Empleados
    join p in context.Personas
    on e.Idpersona equals p.Idpersona
    select new { e, p };

but it is an anonymous type and I don't know how to map it to an employee list, also try to do this:

var queryable = from e in context.Empleados
                            join p in context.Personas
                            on e.Idpersona equals p.Idpersona
                            select new Empleado
                            { Noemp = e.Noemp, 
                              Nombre = p.Nombre
                            };

but employee does not have the person properties and it gives me an error.

in the end I tried to use a dto but I don't want to do a dto for each table that I have to relate when an include would solve it

List<Empleado> listadeempleados = new List<Empleado>();
var personas = await context.Personas.ToListAsync();

    foreach(var item in personas)
    {
        var empleado = await context.Empleados.Where(x => x.Idpersona == item.Idpersona).FirstOrDefaultAsync();
        listadeempleados.Add(empleado);
    }
        var model = new EmpleadoPersonaListDTO();
        model.ListaEmpleados = listadeempleados;
        model.ListaPersonas = personas;

I can't find how to work with Entity Framework and tables that are not related to foreign keys, I know I should have keys but that's how the database was made and I can't change it

You don't need foreign keys in the database to declare Navigation Properties in EF. Just create the EF model as if the foreign keys were there. And of course don't update the database with Migrations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM