简体   繁体   English

带有MySql的实体框架:将System.Guid映射到VARCHAR(40)

[英]Entity Framework with MySql: Map System.Guid to VARCHAR(40)

I am using Entity Framework 6 code first to connect to a MySql database. 我首先使用Entity Framework 6代码连接到MySql数据库。 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). 我也不能更改为其他形式的Entity Framework(首先是模型或数据库)。

I'm having trouble mapping my POCO object to a particular table 我在将POCO对象映射到特定表时遇到问题

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. 我知道,“ id”列始终是Guid。 Therefore I have created my POCO class as follows: 因此,我创建了如下的POCO类:

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. 据我了解,EF for MySql只会将VARCHAR列映射到POCO中的字符串字段。 Is there any way I can tell entity framework that the 'id' column should be converted from a VARCHAR(40) to a Guid? 我有什么办法可以告诉实体框架“ id”列应从VARCHAR(40)转换为Guid?

I was thinking of accepting that I could not map to a Guid. 我当时正在考虑接受我无法映射到Guid。 I'd just map to a string and create a custom getter method: 我只是映射到一个字符串并创建一个自定义的getter方法:

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. 请帮助EF newb。 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. 我希望如果VARCHAR(40)无法解析为Guid,则实体框架只会抛出异常。 That is not the case with the MySQL provider. MySQL提供程序不是这种情况。

I ended up declaring my Id member as a string. 我最终将Id成员声明为字符串。 To keep my POCO class a true POCO class, I created a helper method to convert strings to Guids. 为了使我的POCO类保持真正的POCO类,我创建了一个辅助方法来将字符串转换为Guid。

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. 因此,可以使用IMyTable而不是使用MyTable来获取具有期望类型的字段的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM