[英]entity framework custom data type mapping
Given this code:鉴于此代码:
public class Car
{
public virtual int CarId { get; set; }
public virtual string TypeName { get; set; }
public ConvertableNullable<double> Price { get; set; }
}
Where the ConvertableNullable
is just a workaround to Nullable
, but it doesn't inherit from it. ConvertableNullable
只是Nullable
的一种解决方法,但它不继承自它。
Now, this my simple context, where i map, the car class to entity, and map every property of it现在,这是我的简单上下文,其中我 map,汽车 class 到实体,以及 map 它的每个属性
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; }
}
now when i try to deal with this context, it throws an exception现在,当我尝试处理这种情况时,它会引发异常
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();
Any suggestions??有什么建议么??
The only solution is using something like this:唯一的解决方案是使用这样的东西:
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 }
}
}
Your mapping will be:您的映射将是:
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);
The problem is that EF globally doesn't have support for custom scalar types.问题是 EF 全局不支持自定义标量类型。
"Make sure that it is a valid primitive property" - clearly the problem lies with your Nullable workaround - why not just make it a nullable double? “确保它是一个有效的原始属性”——显然问题出在你的 Nullable 解决方法上——为什么不把它变成一个可以为 null 的 double 呢?
public class Car
{
public virtual int CarId { get; set; }
public virtual string TypeName { get; set; }
public double? Price { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.