為了說(shuō)明什么是復(fù)雜屬性,先舉一個(gè)例子。
public class CompanyAddress
{
public int ID { get; set; }
public string CompanyName { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
public class FamilyAddress
{
public int ID { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
上面有兩個(gè)類(lèi):公司地址和家庭地址,它們有四個(gè)相同的屬性:StreetAddress、City、State、ZipCode。映射到數(shù)據(jù)庫(kù)中的結(jié)構(gòu)如圖:
這里,我們可以將這四個(gè)屬性集合成一個(gè)復(fù)雜屬性Address,修改后的類(lèi)為:
public class CompanyAddress
{
public int ID { get; set; }
public string CompanyName { get; set; }
public Address Address { get; set; }
}
public class FamilyAddress
{
public int ID { get; set; }
public Address Address { get; set; }
}
[ComplexType]
public class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
此時(shí),所生成的數(shù)據(jù)庫(kù)如圖:
可以看到,兩張表中仍然具有相應(yīng)的地址屬性信息。代碼中的Address類(lèi)就是復(fù)雜屬性,它并不會(huì)在數(shù)據(jù)庫(kù)中映射成相應(yīng)的表,但我們的代碼確簡(jiǎn)潔了許多。
所以如果有幾個(gè)屬性在幾個(gè)類(lèi)中都有用到,那么就可以將這幾個(gè)屬性集合成一個(gè)復(fù)雜類(lèi)型,并在相應(yīng)的類(lèi)中增加這個(gè)復(fù)雜類(lèi)型的屬性。