Reputation: 33
I'm trying to create a one to many relationship using entity framework to convert the json object using Web.API return.
I am creating a scenario that a User has many features emails.
However json file in the User entity that brings contains a list of Emails that appear always empty.
User Entity
[DataContract]
public class UsuarioEntity : BaseEntity
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public bool Ativado { get; set; }
[DataMember]
public ICollection<EmailEntity> Emails { get; private set; }
}
Email Entity
[DataContract]
public class EmailEntity : BaseEntity
{
[DataMember]
public string Email { get; set; }
[DataMember]
public bool Ativo { get; set; }
[DataMember]
public bool Principal { get; set; }
[DataMember]
public DateTime DataCadastro { get; set; }
[DataMember]
public UsuarioEntity Usuario { get; set; }
}
Fluent API
UsuarioConfiguration
ToTable("tbl_usuarios");
HasKey(a => new {a.Id, a.UserName});
Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnName("cd_id_usuario");
Property(a => a.UserName)
.HasMaxLength(32)
.HasColumnName("nm_usuario");
Property(a => a.Password)
.IsRequired()
.HasMaxLength(32)
.HasColumnName("tx_senha");
Property(a => a.DataCadastro)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)
.HasColumnType("datetime")
.IsRequired()
.HasColumnName("dt_cadastro");
HasMany(o => o.Emails)
.WithRequired();
EmailConfiguration
ToTable("tbl_email_usuario");
HasKey(a => new { a.Id, a.Email });
Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnName("cd_id_email");
Property(a => a.Email)
.HasMaxLength(150)
.HasColumnName("nm_email");
Property(a => a.DataCadastro)
.HasColumnType("datetime")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)
.IsRequired()
.HasColumnName("dt_cadastro")
I tried to use EF with Web api this way:
public IQueryable<UsuarioEntity> Get()
{
PlainContext context = new PlainContext();
return context.Usuarios;
}
Except that the return was not expected
[{"Id":1,"Ativado":true,"DataCadastro":"\/Date(1357307720730-0200)\/","Emails":[],"Password":"senha456","UserName":"recapix"}]
I own and Registered Emails only they do not appear on Json.
Upvotes: 2
Views: 3228
Reputation: 364409
Your entities don't support lazy loading so you must define explicitly that you want to load related emails as well:
return context.Usarios.Include(u => u.Emails);
Upvotes: 1