Entity Framework 復雜類型


為了說明什么是復雜屬性,先舉一個例子。

 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類就是復雜屬性,它並不會在數據庫中映射成相應的表,但我們的代碼確簡潔了許多。

所以如果有幾個屬性在幾個類中都有用到,那么就可以將這幾個屬性集合成一個復雜類型,並在相應的類中增加這個復雜類型的屬性。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM