I am using Entity Framework 6 code first to connect to a MySql database. I do not own the database. I cannot change the database schema. I also cannot change to another flavor of Entity Framework (model or database first).
I'm having trouble mapping my POCO object to a particular table
The table is as follows:
CREATE TABLE 'my_table' (
'id' VARCHAR(40) NOT NULL,
'name' VARCHAR(200),
Primary Key ('id')
)
I know for a fact that the 'id' column will always be a Guid. Therefore I have created my POCO class as follows:
public class MyTable
{
public Guid Id { get; set;}
public string Name { get; set;}
}
From my understanding EF for MySql will only map VARCHAR columns to string fields in your POCO. Is there any way I can tell entity framework that the 'id' column should be converted from a VARCHAR(40) to a Guid?
I was thinking of accepting that I could not map to a Guid. I'd just map to a string and create a custom getter method:
public class MyTable
{
public string Id { get; set;}
public string Name { get; set;}
public Guid GetId()
{
Guid id;
if (Guid.TryParse(this.Id, out id))
return id;
else
return new Guid();
}
}
Please help an EF newb out. Thanks
I could not find a way to do this. I was hoping that entity framework would just throw an exception if the VARCHAR(40) could not be parsed to a Guid. That is not the case with the MySQL provider.
I ended up declaring my Id member as a string. To keep my POCO class a true POCO class, I created a helper method to convert strings to Guids.
You may want to use interface for that and use explicit implementation.
public interface IMyTable
{
Guid Id { get; set; }
string Name { get; set; }
}
public class MyTable : IMyTable
{
public string Id { get; set; }
public string Name { get; set; }
// use explicit implementation for Id
Guid IMyTable.Id
{
get => Guid.Parse(this.Id);
set => this.Id = value.ToString();
}
}
So instead of using MyTable, you can use IMyTable to get object with fields that have the expected types.