Problem mapping entities related to Fluent API

Asked

Viewed 160 times

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

inserir a descrição da imagem aqui

2.2 Timesoccer Table

Table name: Timesoccer

inserir a descrição da imagem aqui

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

inserir a descrição da imagem aqui

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).

inserir a descrição da imagem aqui

  • 1

    Please show code in text, not images.

3 answers

0

You did not put in question the code that performs the data query using the context and this makes it difficult to answer.

However, most likely using the Include as the code below you will be able to load the Timesoccer related to the User.

Example:

public ICollection<Usuario> GetAll()
{
    return context.Usuario.Include("TimeFutebol").ToList();
}
  • Renan, includes the query classes in the post.

  • Using the Include command as exemplified in the reply you were able to search users with your respective team?

0

Change your Timefootball class to:

public class TimeFutebol
{
    public TimeFutebol()
    {
        Usuarios = new List<Usuario>();
    }

    public int TimeFutebolId { get; set; }
    public string TimeFutebolNome { get; set; }

    public ICollection<Usuario> Usuarios { get; set; }
}

Functional example: https://dotnetfiddle.net/9YnnEs

  • Cassio Alves, I made the adjustment you mentioned and updated the post because of it.

  • after the change, it worked?

  • He kept presenting the same problem. The only difference is that the Usuarios property, of the Timefutebol class, no longer appears as null, because I installed it in the constructor of its class (Timefutebol).

  • and how do you save the data? could you put an example. Note: you do not need to implement a repository: https://answall.com/questions/51536/quando-usar-entity-framework-com-repository-pattern/80696

  • Well, for me to save the data, first I have to work with them. For this, I need to first popular my classes with the database data. That’s where my problem is, I’m not getting my classes popular. Answering your question, to save the data after I perform some Add, Update or Delete, I will call the Saveall method I implemented in the Irepository Interface.

  • could put an example? because it is unnecessary in my view.

  • Cassio, I think this is going to come out of my doubt, which is just how to fill my classes automatically with the Fluent API. I would like to solve this problem first, because it is preventing me from continuing in my studies. Later, if I have any problem saving the data, I will turn to you.

  • That’s right. You could put the code you use to save, from class instantiation, to savechanges.

  • All the classes, methods, properties and interfaces I use in the application I’m studying, were shown in the post, with images and codes. I haven’t forgotten anything. I just didn’t put App.config, because the connection to the bank is being made. I know this because some data of the classes are being filled in, such as user name and email, for example.

Show 5 more comments

0


I only included the virtual in the navigation properties and worked. Example of one of the properties:

public virtual ICollection<Usuario> Usuarios { get; set; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.