I have been using a custom type for Money with my POCOs and tries to insert this to my database but it is implicitly thrown away by Entity Framework.
This is my code made simple;
My type;
public struct Money
{
private static decimal _value;
public Money(Decimal value)
{
_value = value;
}
public static implicit operator Money(Decimal value)
{
return new Money(value);
}
public static implicit operator decimal(Money value)
{
return _value;
}
}
My object;
public class MyObject
{
[Key]
public int Id { get; set; }
public Money MyMoney { get; set; }
}
My context;
public class Data : DbContext
{
public Data()
: base("Data Source=.;Database=MyTest;Integrated Security=True")
{}
public DbSet<MyObject> MyObject { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyObject>()
.Property(p => p.MyMoney).HasColumnName("MyMoney");
}
}
When I use this code I get the following error.
The property ‘MyMoney’ is not a
declared property on type ‘MyObject’.
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.
I guess the problem is the last sentence…. Then, what is a valid primitive property? Is there any other way to take care of this?
Ok, this went to be my solution.
To be able to read that private property I created a property extension as below. Since some of my properties of type Money is Nullable I had to take care of that as well.
And then I could use that to read my private property.
Thank you Steve for taking me in the right direction.