EF Core CodeFirst代码优先中的复杂类型
复杂类型在EF 4.1中很容易实现。想象客户实体类有一些像城市,邮政编码和街道的属性,我们发现把这些属性
组织成一个叫地址的复杂类型会比较好。
//Initial Customer Entity // public class Customer : Entity { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string City { get; set; } public string Street { get; set; } public string ZipCode { get; set; } } Figure 22.- Initial plain Customer entity //Initial Customer Entity // public class Customer : Entity { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Address Address { get; set; } } public class Address { public string City { get; set; } public string Street { get; set; } public string ZipCode { get; set; } }
考虑到我们不需要做其他任何事,EF转换会处理好复杂类型和映射到数据库中。默认转换会是
[复杂类型名]_[属性名]。因此,SQL schema会是这样的。
CREATE TABLE [dbo].[Customers]( [CustomerId] [int] IDENTITY(1,1) NOT NULL, [FirstName] [nvarchar](128) NULL, [LastName] [nvarchar](128) NULL, [Address_City] [nvarchar](128) NULL, [Address_ZipCode] [nvarchar](128) NULL, [Address_Street] [nvarchar](128) NULL, PRIMARY KEY CLUSTERED ( [CustomerId] ASC Address complex type )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
我们可以修改这样的映射。如果我们用“Fluent API‟的方法,我们会使用DbModelBuilder类的ComplexType
方法,就像下面的代码。
//Using ‘ComplexType()’ method Fluent API – (Code in Data Persistence Infr.Layer) // protected override void OnModelCreating(DbModelBuilder modelBulder) { modelBuilder.Entity<Customer>() .Ignore(c => c.FullName); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.ComplexType<Address>() .Property(p => p.City) .HasColumnName("City"); modelBuilder.ComplexType<Address>() .Property(p => p.Street) .HasColumnName("Street"); modelBuilder.ComplexType<Address>() .Property(p => p.ZipCode) .HasColumnName("ZipCode"); }
ComplexType<>提供和Entity<>一样的配置。
我们也可以把自定义映射的关系放到新派生于ComplexTypeConfiguration<TComplexType>的类中。
class AddressComplexTypeConfiguration :ComplexTypeConfiguration<Address> { public AddressComplexTypeConfiguration() { this.Property(p => p.ZipCode) .HasColumnName("ZipCode"); Using the ComplexType method (Fluent API) NOTE: ComplexType<> does offer the same configuration possibilities than Entity<>. this.Property(p => p.Street) .HasColumnName("Street"); this.Property(p => p.City) .HasColumnName("City"); } }
然后我们需要将它添加到OnModelCreating()方法的配置列表。这是复杂项目的推荐做法,这样我们
可以更好的构造它们。
public class MainBCUnitOfWork : DbContext { public IDbSet<Customer> Customers { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new AddressComplexTypeConfiguration()); } }
标签:Core,set,string,get,EF,Entity,ComplexType,public From: https://www.cnblogs.com/cdaniu/p/16818997.html