標籤:blog http 資料 re c 代碼
為了說明什麼是複雜屬性,先舉一個例子。
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; } }
上面有兩個類:公司地址和家庭地址,它們有四個相同的屬性:StreetAddress、City、State、ZipCode。映射到資料庫中的結構
這裡,我們可以將這四個屬性集合成一個複雜屬性Address,修改後的類為:
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; } }
此時,所產生的資料庫
可以看到,兩張表中仍然具有相應的地址屬性資訊。代碼中的Address類就是複雜屬性,它並不會在資料庫中映射成相應的表,但我們的代碼確簡潔了許多。
所以如果有幾個屬性在幾個類中都有用到,那麼就可以將這幾個屬性集合成一個複雜類型,並在相應的類中增加這個複雜類型的屬性。