Julen
Julen

Reputation: 1604

Entity Framework code first using models defined with non-native types

I have a question regarding EF Code First with MVC. Currently I know how to create controllers and views out a model that has all the atributtes as native types such as (int, string, etc.).

What if I have a model that one its attributes is a type defined in another model in my project?

Something like

public class Partido
    {
        public int ID { get; set; }
        public Seleccion Local { get; set; }
        public Seleccion Visitante { get; set; }
        public Resultado Marcador { get; set; }
    }

Where Seleccion and Resultado are defined each one in the same model namespace of the project.

Upvotes: 0

Views: 126

Answers (1)

lucask
lucask

Reputation: 2290

Decorate Seleccion and Resultado classes with ComplexType attribute. Example:

public class Partido
{
    public int ID { get; set; }
    public Seleccion Local { get; set; }
    public Seleccion Visitante { get; set; }
    public Resultado Marcador { get; set; }
}

[ComplexType]
public class Seleccion {} 

[ComplexType]
public class Resultado {}

Entity Framework will generate appropriate colums in 'Partido' table that will correspond to Seleccion and Resultado class properties.

You can learn more about it here: Code First Data Annotations

Upvotes: 1

Related Questions