开发者

How to map abstract class using entity code first and State Pattern

I'm trying mapp an entity using Entity Framwork 4.1, Code First and Fluent API. My scenary is that I'm implementing an State Pattern using an abstract class. See my implementation:

//my contract

public abstract class SaleStatus
{
        public int IdSaleStatus { get; set; }
        public string Description { get; set; }

        public abstract void ChangeTo(Sale sale, SaleStatus saleStatus);
}

public class SaleStatusBooked : SaleStatus
{
        public SaleStatusBooked()
        {
            this.IdSaleStatus = 1;
            Description = "Reservado";
        }

        public override void ChangeTo(Sale sale, SaleStatus newStatus)
        {
            if (!(newStatus is SaleStatusPaid) || (!(newStatus is SaleStatusTimeOut)))
                throw new BusinessException("salestatus");

            sale.SetStatus(newStatus);
        }
}

    public class SaleStatusPaid : SaleStatus
    {
        public SaleStatusPaid()
        {
            this.IdSaleStatus = 2;
            Description = "Pago";
        }

        public override void ChangeTo(Sale sale, SaleStatus newStatus)
        {
            if (!(new开发者_如何学JAVAStatus is SaleStatusCancelled) || (!(newStatus is SaleStatusNotResolved)) || (!(newStatus is SaleStatusCriticalError)))
                throw new BusinessException("salestatus");

            sale.SetStatus(newStatus);
        }
    }

And Now, my current mapping of SaleStatus:

    public class SaleStatusMap: EntityTypeConfiguration<SaleStatus>
    {
        public SaleStatusMap()
        {
            ToTable("SaleStatus");
            HasKey(ss => ss.IdSaleStatus);

            Map<SaleStatusBooked>(pk => pk.Requires("IdSaleStatus").HasValue(1));                
            Map<SaleStatusPaid>(pk => pk.Requires("IdSaleStatus").HasValue(2));         
        }
    }

When I run my project I received this message:

Schema specified is not valid. Errors: (107,6) : error 0075: Key Part: 'IdSaleStatus' for type SaleStatus is not valid. All parts of the key must be non nullable.

Anyone can help me?

Thanks,

Best Regards.

Michel Magalhães


You are trying to use the Primary Key column as the discriminator. This is not supported. EF does not allow you to map the discriminator column as a property(EF internally assigns the correct discriminator value when you are saving new derived type)

What you can do is create another column in SaleStatus table to store the discriminator value.

public class SaleStatusMap: EntityTypeConfiguration<SaleStatus>
{
    public SaleStatusMap()
    {
        ToTable("SaleStatus");
        HasKey(ss => ss.IdSaleStatus);

        Map<SaleStatusBooked>(pk => pk.Requires("StatusType").HasValue(1));                
        Map<SaleStatusPaid>(pk => pk.Requires("StatusType").HasValue(2));         
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜