4

In EF Core you can convert a value from one type to another in the following manner:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyClass>()
    .Property(x => x.MyProperty)
    .HasConversion(
        v => ...
        v => ...
    )
}

I know this feature is not supported in EF6 but what would be a workaround to accomplish the same thing? The problem in my case is that I have to convert a varchar field to a Guid and I can't change the type directly in the database to an uniqueidentifier unfortunately. Note: This will used together with odata.

Just doing this:

[EnableQuery]
public IHttpActionResult Get()
{
    return Ok(from p in db.Persons
        select new Person
        {
            Guid = Guid.Parse(p.GuidString),
            Name = p.Name
        });
}

would result in the error:

LINQ to Entities does not recognize the method 'System.Guid Parse(System.String)' method, and this method cannot be translated into a store expression.

Marty78
  • 87
  • 7
  • the reason https://stackoverflow.com/a/35402926/17447 – naveen Mar 07 '21 at 09:48
  • @naveen Yeah, I found that answer prior to asking my question but adding "let guid = Guid.Parse(p.GuidString)" and then referencing guid in "Guid = guid" results in the same error unfortunately. – Marty78 Mar 07 '21 at 11:15
  • `db.Persons.ToList()` or `AsEnumerable()`. That is, do the conversion on the client. – Alexander Petrov Mar 07 '21 at 11:22
  • @naveen The closest to what I am trying to accomplish is this question from 7 years ago. The question is if anything has been implemented to handle this directly in LINQ since then: https://stackoverflow.com/questions/20062549/how-can-i-parse-a-string-into-a-uniqueidentifier – Marty78 Mar 07 '21 at 11:33
  • Could you create a function in the db to perform the cast and then use Ef function mapping so you can call something like MyDbFunctions.ToGuid in the select? – pinkfloydx33 Mar 07 '21 at 12:00
  • @pinkfloydx33 Thank you for the tip. That might actually be a plausible workaround. I would had wished LINQ would had been able to handle a simple cast however. – Marty78 Mar 07 '21 at 12:18
  • @Marty78: Casting in DB should be a good way to go performance wise. But not that good maintainance wise. I now a days usually use automapper – naveen Mar 07 '21 at 12:40

0 Answers0