one for many and many for an Entity Framework

2

I'm developing these classes in this diagram, but I'm not sure how to declare relationships [One for many, many for one]

Here's the diagram:

forexampleProducthasaCategory,andCategoryhasseveralProducts:

publicclassProduto{[Key]publicintCodigo{get;set;}[Display(Name="Descrição")]
    public string Descricao { get; set; }

    [Display (Name = "Preço de Compra")]
    public double PrecoCompra { get; set; }

    [Display (Name = "Preço de Venda")]
    public double PrecoVenda { get; set; }

    public double Desconto { get; set; }
    public string Imagem { get; set; }
    public string Garantia { get; set; }
    public string Fabricante { get; set; }

}

Category

public class Categoria
{
    public int Codigo { get; set; }

    public string Nome { get; set; }
    public double Desconto { get; set; }
}

How do I declare them for EF to understand these relationships?

In this diagram, to declare the person class that has address I did:

    public class Pessoa
{
    [Key]
    public int Codigo { get; set; }
    ...
    public int EnderecoId { get; set; }
    public Endereco Endereco { get; set; }
}

Is this statement correct?

Thankful

    
asked by anonymous 25.10.2017 / 21:57

2 answers

2

You can use the EntityConfig to make this mapping in an elegant and practical way.

It's important to use Virtual in your relationships, this allows the Entity Framework to create a proxy around the property so that the property can support lazy loading and more efficient change tracking.

I've commented on some descriptions.

// virtual ICollection<Products> Products cria uma lista de produtos na categoria ... 
// Virtual permite que o Entity Framework crie um proxy em torno da propriedade virtual 
// para que a propriedade possa suportar //o carregamento preguiçoso e o rastreamento de mudanças mais eficiente. 
public partial class Categories
{
    public Categories()
    {
        Products = new HashSet<Products>();
    }
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public byte[] Picture { get; set; }

    public virtual ICollection<Products> Products { get; set; }
}

// virtual Categories Categories { get; set; } Cria um objeto categoria para cada produto.
public partial class Products
{
    public Products()
    {
        this.OrderDetails = new HashSet<OrderDetails>();
    }

    public int ProductID { get; set; }
    public string ProductName { get; set; } 

    public virtual Categories Categories { get; set; }
}

// Configuração usando o code first 
public class CategoriesConfiguration : EntityTypeConfiguration<Categories>
{
    public CategoriesConfiguration()
    {
        HasKey(p => p.CategoryID);
        Property(p => p.CategoryName).HasColumnType("nvarchar").IsRequired().HasMaxLength(15);
        Property(p => p.Description).HasColumnType("ntext").HasMaxLength(400).IsOptional();
        Property(p => p.Picture).HasColumnType("image").IsOptional();

        ToTable("Categories");

        // HasMany declara que categorias tem varios produtos 
        // WithOptional diz que o produto pode ter ou não uma categoria ..
        HasMany(p => p.Products)
            .WithOptional(p => p.Categories);
    }
}
    
26.10.2017 / 13:54
2

Example 1xN mapping:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int CurrentGradeId { get; set; }
    public Grade CurrentGrade { get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }

    public ICollection<Student> Students { get; set; }
}

public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Grade> Grades { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // configures one-to-many relationship
        modelBuilder.Entity<Student>()
            .HasRequired<Grade>(s => s.CurrentGrade)
            .WithMany(g => g.Students)
            .HasForeignKey<int>(s => s.CurrentGradeId);          }
    }
}

Reference: here

    
26.10.2017 / 13:17