Fluent API relationship questions for EF 5

5

I have two classes:

  • User > Contains your PK (ID).
  • UsuarioP > Contains user ID (FK).

Class User.cs

public Usuario()
{
    this.UsuariosP = new List<UsuarioP>();
}

public int Id { get; set; }

(...)
public virtual ICollection<UsuarioP> UsuariosP { get; set; }

Class User.cs

public partial class UsuarioP
{
    public int Id { get; set; }
    public Nullable<int> IdUsuario{ get; set; }

    public string Login { get; set; }
    (...)

    public virtual Usuario Usuario{ get; set; }
}

The classes have been mapped like this.

I'd like to call the Login that is inside UsuárioP in Usuario . I can not because of their relationship, otherwise I could.

Attempts - I have already created a virtual userP attribute within User. (Unsuccessfully) - I've tried to instantiate it this way:

public string login {get { return this.UsuarioP.Login} } (Sem sucesso)
  • Putting Login into Usuario.cs as [NotMapped] (Unsuccessful)

Important: I want to get the get and set of this attribute. My project is working with controllers , models , and views .

How do I call Login within UsuarioP so that I can use it on User screens?

Note: Working with MVC 4
      EF 5
      Fluent API

    
asked by anonymous 28.09.2015 / 15:21

2 answers

5

There's nothing wrong with your code. The mapping is perfect. There is, indeed, something wrong with the way you are using it.

Usuario has N UsuarioP (cardinality 1 for N). That is, you will also have N Login s, being one for UsuarioP .

You want to implement get and set of Login , but they are already implemented automatically:

public string Login { get; set; }

The Entity Framework will take care of uploading the information to you at the time it is used. You may be using Login incorrectly. I'll give you some examples of how you might be recovering this Login .

1. Iterating over UsuariosP collection

Your View can do the following:

@foreach (var usuarioP in Model.UsuariosP)
{
    <div>@usuarioP.Login</div>
}

2. Finding a specific record

Also in View :

<div>@Model.UsuariosP.First().Login</div>
@{
    var teste = @Model.UsuariosP.FirstOrDefault(u => u.Id == 2);
}
@if (teste != null) {
    <div>@teste.Login</div>
}
    
28.09.2015 / 15:55
0

Your context is probably configured with LazyLoading ) enabled. LazyLoading is used so that the loading of related entities is performed only when we call the mapped property. In the case of MVC this does not work, as access to the information is performed at the client layer, so this load should be disabled.

According to #

    
28.09.2015 / 15:36