开发者

TPH with no other database fields in derived class in Entity Framework 4.1

开发者 https://www.devze.com 2023-03-25 15:48 出处:网络
This is my (simplified) problem. The classes: public class RetailExposure { public int RetailExposureId { get; set; }

This is my (simplified) problem. The classes:

public class RetailExposure
{
    public int RetailExposureId { get; set; }
    public int RetailModelId { get; set; }
}


public class PocRetailExposure : RetailExposure
{
    [NotMapped]
    public string IncidentScore { get; set; }
}

and my OnModelCreating code:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<RetailExposure>().ToTable("dbo.RetailExposure");
        modelBuilder.Entity<RetailExposure>().Map<PocRetailExposure>(p => p.Requires("RetailModelId").HasValue(1).I开发者_运维问答sRequired());
    }

However when I add a new Exposure record:

        context.RetailExposures.Add(new RetailExposure { RetailModelId = 1 });
        context.SaveChanges();

I get the following error:

System.Data.MappingException: 
(6,10) : error 3032: Problem in mapping fragments starting at line 6:Condition 
member 'RetailExposure.RetailModelId' with a condition other than 'IsNull=False'
is mapped. Either remove the condition on RetailExposure.RetailModelId or remove 
it from the mapping.

What I am trying to do is have a base class 'RetailExposure' with derived classes determined from the RetailModelId field. The derived classes contain no properties that are in the database. I seemed to have figured how to configure EF to use RetailModelId as the discriminator, but I still get this error when saving changes.

Any idea on how I need to configure the context to get this to work? Or am I trying to do something that EF does not currently support?

I do realise I could tell EF to just ignore the derived classes entirely, but this is not quite what I want.


Discriminator mustn't be mapped as property in the entity - it is not supported. Discriminator is just a column in the database and it is mapped to actual entity's subtype. If you want to have a discriminator as a property you cannot map TPH. Also if your parent entity is not abstract it must have value defined for discriminator as well.

Something like:

public class RetailExposure
{
    public int RetailExposureId { get; set; }
}

public class PocRetailExposure : RetailExposure
{
    [NotMapped]
    public string IncidentScore { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<RetailExposure>().ToTable("dbo.RetailExposure");
    modelBuilder.Entity<RetailExposure>()
                .Map<RetailExposure>(p => p.Requires("RetailModelId").HasValue(0))
                .Map<PocRetailExposure>(p => p.Requires("RetailModelId").HasValue(1));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号