Reputation: 989
I'm trying to use Entity Framework and face a problem of mismatching types in database with my models.
Specifically I have String
field Date in class and date
in SQL Server database. Due to that I have an error about improper type when loading data into model.
I attached some of my code, were I suppose casting can be applied.
public class MovementMap : EntityTypeConfiguration<Movement>
{
public MovementMap()
{
ToTable("viewMovement", "met");
HasKey(e => e.IdMovement);
Property(r => r.DateMovement).HasColumnName("dateMovement");
//Type of DateMovement - String, but column dateMovement in db has type date.
}
}
How can I convert it when loading or whenever? Would be glad to receive any ideas!
Upvotes: 2
Views: 1446
Reputation: 7818
You could add a Column
attribute to your DateMovement
property in the class. This will tell Entity Framework that the database value is a Date
:
[Column(TypeName="Date")]
public string DateMovement { get; set; }
That being said, I would recommend changing the DateMovement
property to be a DateTime
for consistency.
If you don't want to change the model, you can perform this configuration by adding a HasColumnType
call to your code sample:
public class MovementMap : EntityTypeConfiguration<Movement>
{
public MovementMap()
{
ToTable("viewMovement", "met");
HasKey(e => e.IdMovement);
Property(r => r.DateMovement).HasColumnName("dateMovement").HasColumnType("Date");
}
}
Upvotes: 1