Mapping Code First with Data Annotations

7

I'm creating a project using DataAnnotations mapping with Code First (similar to Hibernate ), without using FluentAPI .

It turns out that by implementing this process, some exceptions are being raised and I believe it is due to DataAnnotations that I am using in the wrong places.

So,

What is the function and usage of DataAnnotations below?

  • [ComplexType]

  • [InverseProperty]

  • [ForeignKey]

  • [ScaffoldColumn]

I'm having a problem with ForeignKeys , but I believe that if I understand the DataAnnotations well, I can solve the exception .

/ em>

    
asked by anonymous 21.06.2014 / 03:10

1 answer

7

[ComplexType]

Specifies that the class in question is a complex type, used for the construction of several other Models .

For example:

[ComplexType]
public class Address
{
    [Key]
    public int AddressId { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
}

public class Person
{
    [Key]
    public int PersonId { get; set; }
    ...
    public Address Address { get; set; }
}

public class Company
{
    [Key]
    public int CompanyId { get; set; }
    ...
    public Address Address { get; set; }
}

A ComplexType can not normally be accessed directly by a data context.

[InverseProperty]

It serves to explicitly indicate a relation N to 1. It is indicated when the name of the property is not standard.

For example:

public class Movimentacao
{
    [Key]
    public int MovimentacaoId { get; set; }
    public int ProdutoId { get; set; }
    public int UsuarioId { get; set; }

    [InverseProperty("UsuariosMovimentaramProdutos")]
    public virtual Produto Produto { get; set; }
    [InverseProperty("UsuariosMovimentaramProdutos")]
    public virtual Usuario Usuario { get; set; }
}

public class Usuario
{
    [Key]
    public int UsuarioId { get; set; }

    ...

    public virtual ICollection<Movimentacao> UsuariosMovimentaramProdutos { get; set; }
}

public class Produto
{
    [Key]
    public int ProdutoId { get; set; }

    ...

    public virtual ICollection<Movimentacao> UsuariosMovimentaramProdutos { get; set; }
}

[ForeignKey]

Explicitly indicates which foreign entity the foreign key property refers to. For example:

public class Usuario
{
    [Key]
    public int UsuarioId { get; set; }

    ...

    public virtual ICollection<Movimentacao> UsuariosMovimentaramProdutos { get; set; }
}

public class Produto
{
    [Key]
    public int ProdutoId { get; set; }
    [ForeignKey("Usuario")]
    public OperadorDeCadastroId { get; set; }

    ...

    public virtual ICollection<Movimentacao> Movimentacoes { get; set; }
    public virtual Usuario OperadorDeCadastro { get; set; }
}

[ScaffoldColumn]

Indicates to the Scaffolding engine whether or not the column should be generated in your View .

Usually used to not put the property in View .

    
21.06.2014 / 05:41