I'm starting with EF and I'm having trouble mapping the relationship between my entities.
1. Entities
There are two entities in the project that I'm using to practice the subject. These are:
- User
- Soccer team
A user has a unique soccer team and 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; }
}
Please note that I created the TimeFoot navigation property for this entity. I also created the TimeFotosId property, because by reading the EF documentation, I found a recommendation on creating a property that will be the foreign key.
1.2 Soccer 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 Users navigation property for this entity.
2. Database
2.1 User Table
Table name: User
I entered the user below in the test table
2.2TimeFootTable
Tablename:TimeFoot
DbContext
publicclassDataContext:DbContext{publicDataContext():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 application
NotethattheTimeFootpropertyofthefirstobjectintheUserslistisempty.AlreadytheUserspropertyofthetimesobjectlist,=0).