1
I am starting with EF and I am having problems to map the relationship between my entities.
1. Entities
There are two entities in the project that I am using to practice the subject. They are:
- User
- Football team
A user has a single football team and this has n users.
1.1 User
public class Usuario
{
public int UsuarioId { get; set; }
public string UsuarioNome { get; set; }
public string UsuarioEmail { get; set; }
public int TimeFutebolId { get; set; }
public TimeFutebol TimeFutebol { get; set; }
}
Note that I created the navigation property Football team for this entity. I also created the property Timefutebolid, because reading the EF documentation, I found a recommendation about creating a property that will be the key.
1.2 Football team
public class TimeFutebol
{
public int TimeFutebolId { get; set; }
public string TimeFutebolNome { get; set; }
public ICollection<Usuario> Usuarios { get; set; }
public TimeFutebol()
{
Usuarios = new List<Usuario>();
}
}
Note that I also created the navigation property Users for this entity.
2. Database
2.1 Table User
Name of the table: User
I entered the user below in the table for test
2.2 Timesoccer Table
Table name: Timesoccer
Dbcontext
public class DataContext: DbContext
{
public DataContext() : base("name=ConnString") { }
public virtual DbSet<Usuario> Usuario { get; set; }
public virtual DbSet<TimeFutebol> TimesFutebol { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Usuario>().ToTable("Usuario");
modelBuilder.Entity<Usuario>().HasKey(x => x.Id);
modelBuilder.Entity<Usuario>().Property(x => x.Id).HasColumnName("UsuarioId");
modelBuilder.Entity<Usuario>().Property(x => x.Nome).HasColumnName("UsuarioNome");
modelBuilder.Entity<Usuario>().Property(x => x.Email).HasColumnName("UsuarioEmail");
modelBuilder.Entity<Usuario>().Property(x => x.TimeFutebolId).HasColumnName("TimeFutebolId");
modelBuilder.Entity<Usuario>().HasRequired(x => x.TimeFutebol).WithMany(x => x.Usuarios).HasForeignKey(x => x.TimeFutebolId);
modelBuilder.Entity<TimeFutebol>().ToTable("TimeFutebol");
modelBuilder.Entity<TimeFutebol>().HasKey(x => x.Id);
modelBuilder.Entity<TimeFutebol>().Property(x => x.Id).HasColumnName("TimeFutebolId");
modelBuilder.Entity<TimeFutebol>().Property(x => x.Nome).HasColumnName("TimeFutebolNome");
base.OnModelCreating(modelBuilder);
}
}
Result after running the application
Note that the Timefootball property, from the first object on the list users, is empty. Already the User property, from the list of objects teams, has no object (Count = 0).
Please show code in text, not images.
– Jéf Bueno