Reputation: 935
I have a problem receiving an entity within my .net core service using entity framework core.
The problem occurs when the data is selected and leads to an exception as soon as I am trying to access my DbSet
.
I am trying to access my db set like this:
When I check the _dbContext.Customers
results view I see the following error:
So it seems like some cast of the data doesn't work. What I don't understand is why this happens. I've checked my model and my database entity and everything should be fine ...
Here's my code:
Model:
[Table("customers")]
public class Customer
{
[Column("id")]
public int Id { get; set; }
[Column("code")]
public string Code { get; set; }
[Column("card_num")]
public string CardNum { get; set; }
[Column("is_valid")]
public bool IsValid { get; set; }
[Column("valid_from")]
public DateTime ValidFrom { get; set; }
[Column("valid_to")]
public DateTime ValidTo { get; set; }
[Column("card_type")]
public CardType CardType { get; set; }
[Column("prepay_balance_cash")]
public decimal PrepayBalanceCash { get; set; }
[Column("prepay_limit_low")]
public decimal PrepayLimitLow { get; set; }
[Column("prepay_limit_high")]
public decimal PrepayLimitHigh { get; set; }
[Column("bc_contract_number")]
public string BcContractNumber { get; set; }
}
public enum CardType
{
Credit = 1,
Prepayment = 2,
PrepaymentAndCredit = 3,
Identification = 4,
CreditAndPrepayment = 5
}
Db Context:
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Customer>().HasKey(c => c.Id);
}
Database Table:
...
I really don't get it. I don't know why this is happening, I've got some other tables implemented the exact same way which work as expected. Just this one doesn't.
Anybody got an idea what's wrong?
Best regards
Upvotes: 2
Views: 1674
Reputation: 26362
Try by setting the precision in your model as described here https://learn.microsoft.com/en-us/ef/core/modeling/relational/data-types
public class Blog
{
[Column(TypeName = "decimal(15, 3)")]
public decimal PrepayBalanceCash { get; set; }
}
Try also with this change
[Column("card_type")]
public Decimal CardType { get; set; }
Upvotes: 1
Reputation: 500
Column Card_Type is defined as numeric(1,0) which will be mapped as a Decimal and your Enum will be of type Int if possible change the database column to INT.
If your using EF Core 2 then try adding a converter in the OnModelCreating,
modelBuilder
.Entity<Customer>()
.Property(e => e.CardType)
.HasConversion<decimal>();
Not tried it so syntax may be off. But having the database store the correct type natively is more performant.
Upvotes: 2
Reputation: 406
CardType property is obvious suspect. I suppose the problem in card_type numeric(1,0)
and enum values are Int32
type.
Upvotes: 1