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

c# – 实体框架自定义数据类型映射,第1张

概述鉴于此代码: public class Car { public virtual int CarId { get; set; } public virtual string TypeName { get; set; } public ConvertableNullable<double> Price { get; set; }} ConvertableNullable只 鉴于此代码:

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();

有什么建议??

解决方法 唯一的解决方案是使用这样的东西:

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全局不支持@R_301_6942@标量类型.

总结

以上是内存溢出为你收集整理的c# – 实体框架自定义数据类型映射全部内容,希望文章能够帮你解决c# – 实体框架自定义数据类型映射所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1227980.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存