I need to know what am I doing wrong, because the generated query doesn’t match with the attributes of the data base table and I think that my class was well type and also the mappings. Here’s my code
public class Usuario
{
#region Atributos
private int _intID = 0;
private Perfil _Perfil_FK = null;
private String _strNombre = "";
private String _strPassword = "";
#endregion
#region Propiedades
public int ID
{
get { return _intID; }
set { _intID = value; }
}
public Nullable<int> IDPerfil_FK { get; set; }
public virtual Perfil Perfil_FK
{
get { return _Perfil_FK; }
set { _Perfil_FK = value; }
}
public String Nombre
{
get { return _strNombre; }
set { _strNombre = value; }
}
public String Password
{
get { return _strPassword; }
set { _strPassword = value; }
}
#endregion
}
My test was only this _db.Usuario()
The Generated Sql query
SELECT
[Extent1].[IDUsuario] AS [IDUsuario],
[Extent1].[IDPerfil_FK] AS [IDPerfil_FK],
[Extent1].[Nombre] AS [Nombre],
[Extent1].[Password] AS [Password],
[Extent1].[PerfilID] AS [PerfilID] <-- this attribute doesn't exit's
FROM [dbo].[Usuario] AS [Extent1];
Here’s my db context class
public class MasterPageAtentoDB : DbContext
{
public DbSet<Pagina> Pagina { get; set; }
public DbSet<Perfil> Perfil { get; set; }
public DbSet<Permiso> Permiso { get; set; }
public DbSet<Usuario> Usuario { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<Usuario>().Property(r => r.ID).HasColumnName("IDUsuario");
modelBuilder.Entity<Pagina>().Property(r => r.ID).HasColumnName("IDPagina");
modelBuilder.Entity<Permiso>().Property(r => r.ID).HasColumnName("IDPermiso");
modelBuilder.Entity<Perfil>().Property(r => r.ID).HasColumnName("IDPerfil");
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
My database Table

Entity Framework doesn’ recognize your property
IDPerfil_FKas the foreign key property for thePerfil_FKnavigation property because you are not following the naming conventions required for automatic FK property detection. As a result EF assumes thatIDPerfil_FKis an ordinary scalar property and thatPerfil_FKhas no exposed FK property in your model and the column in the database has the standard namePerfil_ID(navigation property name + “_” + primary key property name of target entity class).You have three options to fix this:
Name the FK property appropriately (navigation property name + primary key property name of target entity class):
Put a data annotation attribute on the property to indicate that it is a FK property:
Define the FK property in Fluent API:
I would prefer the first option because your mapping of the primary key properties relies on conventions anyway, so it would be consequent to follow the conventions for the foreign key properties too.