I am trying to implement valueobject in asp.net core with ef core. I have money as value object and product which has money as price property. The problem is that money is serialized in product table but deserialization returns null. I tried debug mode but it even doesn't go in money class for deserialization. Note:I used [NotMapped] because migration gave me error that money needs primary key, But I didn't need table for money and I wanted money to be serialized as a price field in product table. my money model:
[NotMapped]
public class Money
{
public static readonly Money Empty = new Money(0);
public decimal Value { get; private set; }
protected Money()
{
}
public Money(decimal value) : this()
{
if (value < 1)
throw new Exception("value is invalid");
Value = value;
}
}
my product model:
public class Product
{
public Product()
{
}
public Product(string name, decimal price)
{
if (string.IsNullOrEmpty(name))
throw new Exception("Name is invalid");
Name = name;
Price = new Money(price);
}
public int Id { get; private set; }
public string Name { get; private set; }
public Money Price { get; private set; }
}
my dbcontext:
public class StoreDbContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=XXX;initial catalog=Basket2;integrated security=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new ProductConfiguration());
//modelBuilder.Entity<Product>()
// .HasKey(lc => new { lc.Id });
}
public DbSet<Order> Orders{ get; set; }
public DbSet<OrderLine> OrderLines{ get; set; }
public DbSet<Product> Products{ get; set; }
}
my productconfiguration:
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
var test= builder.Property(c => c.Price).
HasConversion(c => JsonConvert.SerializeObject(c), c => JsonConvert.DeserializeObject<Money>(c));
}
}