实体框架自定义数据类型映射

时间:2011-04-28 15:16:24

标签: c# mapping ef-code-first entity-framework-4.1 entity-framework-ctp5

鉴于此代码:

public class Car 
{
    public virtual int CarId { get; set; }
    public virtual string TypeName { get; set; }
    public ConvertableNullable<double> Price { get; set; }
}

ConvertableNullable只是Nullable的解决方法,但不会从中继承。

现在,这是我的简单上下文,我将汽车类映射到实体,并映射它的每个属性

public class MyDBContext : DbContext {
   public MyDBContext() : base(
       "data source=.;initial catalog=newDB1;integrated security=True;" + 
        "multipleactiveresultsets=True;App=EntityFramework")
   { }

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

       modelBuilder.Entity<Car>().HasKey(x=>x.CarId);
       modelBuilder.Entity<Car>().Property(x => x.TypeName);
       modelBuilder.Entity<Car>().Property(x => x.Price);
   }

    public DbSet<Car> Cars { get; set; }
}

现在当我尝试处理这个上下文时,它会引发异常

var db = new MyDBContext();

// Throws exception "The property 'Price' is not a declared 
// property on type 'Car'. Verify that the property has not
// been explicitly excluded from the model by using the Ignore
// method or NotMappedAttribute data annotation. Make sure that
// it is a valid primitive property."
var c = db.Cars.ToList(); 

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

唯一的解决方案是使用类似的东西:

public class Car 
{
    public virtual int CarId { get; set; }
    public virtual string TypeName { get; set; }
    // This must be accessible to the mapping 
    public double? PriceData { get; set; } 

    public ConvertableNullable<double> Price 
    { 
        get { // Return data from PriceData }
        set { // Set data to PriceData }
    }
}

您的映射将是:

modelBuilder.Entity<Car>().HasKey(x=>x.CarId);
modelBuilder.Entity<Car>().Property(x => x.TypeName);
modelBuilder.Entity<Car>().Property(x => x.PriceData).HasColumnName("Price");
modelBuilder.Entity<Car>().Ignore(x => x.Price);

问题是EF全局不支持自定义标量类型。

答案 1 :(得分:0)

“确保它是一个有效的原始属性” - 显然问题在于你的Nullable解决方法 - 为什么不让它成为可以为空的双重?

public class Car 
{
    public virtual int CarId { get; set; }
    public virtual string TypeName { get; set; }
    public double? Price { get; set; }
}