-2

In my code first app I do have a class "customer" and "address". My client class has Address class reference. for instance

class Customer{
    public string name {get;set;}
    public Address address {get;set;}
}

class Address{
    public string street{get;set;}
    public string number{get;set;}
}

when I migrate these data I got one table customer with those columns:

name
address_street
address_number

It is great. My data is only in one table. It was perfect to me!.

However I need (for other reasons) add a ID for address.

class Address{
    [Key]
    public int EnderecoId { get; set; }
    public string street{get;set;}
    public string number{get;set;}
}

in this case the migration split my customer table into customer and address table.

name
addressId

and

street
number

There is any annotation that could avoid this ? I really would like to have address data inside customer table.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Daniel Santos
  • 14,328
  • 21
  • 91
  • 174
  • 1
    Not sure why you don't go the normalized route: https://msdn.microsoft.com/en-us/data/jj713564.aspx?f=255&MSPPError=-2147217396, but you could add [NotMapped] to your Id. http://stackoverflow.com/questions/10572442/how-to-ignore-a-property-when-using-entity-framework-code-first – Steve Greene Jul 19 '16 at 14:45
  • What happens when someone has two addresses? Completely agreed with @SteveGreene that normalization is the way to go. – krillgar Jul 19 '16 at 14:46
  • Guys I understand your point. Please note that this is a example to express my needs. The real data is not a address. is quite more complex. But i appreciate your concern. – Daniel Santos Jul 19 '16 at 14:51

1 Answers1

0

In order for code first to recognize this, you must mark the Address class as a [ComplexType]. Then Address will be tracked as part of a Customer object.

Just add the [ComplexType] annotation into the address class

[ComplexType]
public class Address
{ 
    //...
}
Daniel Santos
  • 14,328
  • 21
  • 91
  • 174