实体框架自定义数据类型映射
给定以下代码:
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();
有什么建议吗?
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.
Now, this my simple context, where i map, the car class to entity, and map every property of it
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
唯一的解决方案是使用这样的东西:
您的映射将是:
问题是 EF 全局不支持自定义标量类型。
The only solution is using something like this:
Your mapping will be:
The problem is that EF globally doesn't have support for custom scalar types.
“确保它是一个有效的原始属性” - 显然问题出在你的 Nullable 解决方法上 - 为什么不把它变成一个可以为 null 的双精度呢?
"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?