2

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!

3
  • 2
    My recommendation is that you change the type in your class to a DateTime if you can. If not, check out DateTime.Parse and DateTime.ParseExact. Commented Feb 1, 2016 at 14:14
  • I try not to change the model now. Can you suggest where exactly should I use parsing? Commented Feb 1, 2016 at 14:22
  • tbh - the minimal pain in changing to a DateTime column now will FAR outweigh the neglect further down the road- the old adage horses for courses Commented Feb 1, 2016 at 14:39

1 Answer 1

1

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"); 
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I'll change type of the property and I'm absolutely agree with you. But I was really intrested in solving this problem another way - if i couldn't change the model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.