Nov 25, 2014
1 min read
Complex Type是用來重覆使用的欄位,有幾個規定 1. 不能有主索引 2. 一個類別中只能有一個實體 3. 只能是引用屬性,不能是集合屬性
Table1
namespace ConsoleApplication1.Models { public class Table1 { public int Table1Id { get; set; } public Address Address { get; set; } } }
namespace ConsoleApplication1.Models { public class Table2 { public int Table2Id { get; set; } public Address Address { get; set; } } }
namespace ConsoleApplication1.Models { public class Address { public string Addr1 { get; set; }public string Addr2 { get; set; } }
}
namespace ConsoleApplication1.Models { using System.ComponentModel.DataAnnotations.Schema;[ComplexType] public class Address { [Column("Addr1")] public string Addr1 { get; set; } [Column("Addr2")] public string Addr2 { get; set; } }
}
namespace ConsoleApplication1.Models { using System.Data.Entity; using System.Data.Entity.ModelConfiguration;public class DemoContext : DbContext { public DbSet<Table1> Table1 { get; set; } public DbSet<Table2> Table2 { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new AddressConfiguration()); } private class AddressConfiguration : ComplexTypeConfiguration<Address> { public AddressConfiguration() { this.Property(x => x.Addr1).HasColumnName("Addr1"); this.Property(x => x.Addr2).HasColumnName("Addr2"); } } }
}
Sharing is caring!