HappyNomad
HappyNomad

Reputation: 4548

Map type to string

If I have a type like this

public class SomeType
{
    public string Text { get; set; }
    // Other properties that are not mapped...
}

in which there is only one mapped property which is of type string, how do I map all references to SomeType to a simple text column (the value of SomeType.Text) and thus avoid generating a SomeType table?

Upvotes: 4

Views: 815

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

If SomeType is not defined as entity (i.e. there is no DbSet<SomeType> in your context), then it is a Complex Type and it's value will be stored in same table as entity which uses your complex type. So, if you have entity Customer like this:

public class Customer
{
    public SomeType Foo { get; set; }
    // other members
}

Then in Customers table you will have column Foo_Text. Separate table for SomeType will not be created. The only restriction with complex types is that you can't have null value for them.


Also you can specify mappings for your complex type if default column name EntityPropertyName_ComplexTypePropertyName does not suits your needs:

modelBuilder.ComplexType<SomeType>()
            .Property(st => st.Text).HasColumnName("Text");

Upvotes: 1

Related Questions