实体框架6条件映射首先使用代码

时间:2016-12-02 11:44:04

标签: c# entity-framework-6

我有点困惑如何实现这一目标。我找到了一篇在线文章,其中解释了如何解决这个问题非常好,但采用了不同的方法,我现在正在追逐。情况就是这样: 我有一个DbContext继承类,我在其中覆盖OnModelCreatin函数,如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //base.OnModelCreating(modelBuilder);

        //Configure default schema
        modelBuilder.HasDefaultSchema("public");

        modelBuilder.Configurations.Add(new EmailMapping());
        modelBuilder.Configurations.Add(new CustomerEmailMapping());

    }

CustomerEmailMapping类是EntityTypeConfiguration<CustomerEmail>派生类。在构造函数中,我映射了所需的任何内容

class CustomerEmailMapping : EntityTypeConfiguration<CustomerEmail>
{
    public CustomerEmailMapping()
    {
        ToTable("customer_email");
        HasKey<long>(ce => ce.ID);

        Property(ce => ce.ID)
                .HasColumnName("id");

        Property(ce => ce.CustomerID)
                .HasColumnName("customer_id");

        Property(ce => ce.EmailID)
                .HasColumnName("email_id");

        Property(ce => ce.Note)
                .HasColumnName("note");

        Property(ce => ce.IsMain)
                .HasColumnName("is_main");

        //Property(ce => ce.OwnerType)
        //       .HasColumnName("owner_type");

        HasRequired<Customer>(c => c.Owner)
                .WithMany(s => s.Emails);

        HasRequired<Email>(c => c.Email)
                .WithMany(c => c.CustomerEmails);


        //here on this row it gets the error
        Map(p => p.Requires("OwnerType").HasValue(0)).Ignore(ce=>ce.OwnerType);


    }
}

以下是我得到的异常的堆栈跟踪:

at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.AddMappingConfiguration(EntityMappingConfiguration mappingConfiguration, Boolean cloneable)
at System.Data.Entity.ModelConfiguration.EntityTypeConfiguration`1.Map(Action`1 entityMappingConfigurationAction)
at VisaFirst.DataAccess.Mappings.CustomerEmailMapping..ctor() in C:\D\Projects\C#\VisaFirst\VisaFirst.DataAccess\Mappings\CustomerEmailMapping.cs:line 39
at VisaFirst.DataAccess.SQLDataService.OnModelCreating(DbModelBuilder modelBuilder) in C:\D\Projects\C#\VisaFirst\VisaFirst.DataAccess\SQLDataService.cs:line 117
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy``2.GetValue(TInput input)`

我明白这样做的文章是this one 请任何人都能告诉我我做错了什么?

提前致谢, 儒略

解决方案:THIS HELPED ME SOLVE THE PROBLEM DESCRIBED IN THE POST.感谢@SteveGreene

0 个答案:

没有答案