Mapping entity user data types

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 ConvertableNullable is just a workaround to Nullable , but it does not inherit from it.

Now, this is my simple context, where I map a car class to an entity and map each of its properties

 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

+4
source share
2 answers

The only solution uses 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 does not support user-defined scalar types worldwide.

+1
source

β€œMake sure this is a valid property of the primitive” - it’s clear that the problem is with the Nullable workaround - why not just make it double with a null value?

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

Source: https://habr.com/ru/post/909383/


All Articles