Reputation: 3
I have a model
public class Role
{
public int id { get; set; }
public string name { get; set; }
public string shortname { get; set; }
}
public class User
{
public int id { get; set; }
public string login { get; set; }
public int idrole { get; set; }
public DateTime regdate { get; set; }
public int idregistred { get; set; }
public virtual Role role { get; set; }
}
And I'm create the repository and load data:
public class Repository
{
public IQueryable<TEntity> Select<TEntity>()
where TEntity : class
{
var context = new QContext();
return context.Set<TEntity>();
}
}
var rep = new Repository();
var roles = rep.Select<User>().Include(el => el.role).ToList();
When I load the data, I have error:
column Extent1.role_id does not exist
Generated SQL:
SELECT "Extent1"."id", "Extent1"."login", "Extent1"."idrole", "Extent1"."regdate", "Extent1"."idregistred", "Extent2"."id" AS "id1", "Extent2"."name", "Extent2"."shortname" FROM "questionnaire"."user" AS "Extent1" LEFT OUTER JOIN "questionnaire"."role" AS "Extent2" ON "Extent1"."role_id" = "Extent2"."id"
But in database I have not column "role_id". In "questionnaire"."user" I have only "idrole".
How I can load the data? Why entity create incorrect sql code? How fix it?
I use entity framework v6.1.3, Npgsql v2.2.7 and Npgsql.EntityFramework v2.2.7
Upvotes: 0
Views: 344
Reputation: 31193
Entity Framework can't guess how you have linked the tables to each other. The default way is adding _id
to the field name, which results in role_id
. You have to tell EF what the actual column is for it to work. You can do this by using ForeignKeyAttribute
:
[ForeignKey("idrole")]
public Role role { get; set; }
This way EF knows the column idrole
is used to reference the role
table.
Upvotes: 0