2

I have just done the equivalent of Hello World by creating an Entity Framework Code First model (I have written other C# programs but not with Entity Framework). I created a model like this:

class Preferences
{
    [Key]
    public string StationName { get; set; }
    [MaxLength(30)]
    public string MainDatabase { get; set; }
    [MaxLength(30)]
    public string DefaultSequence { get; set; }
}

and then had a little routine to add a record

var newPrefs = new Preferences
{
    StationName = "MATT",
    DefaultSequence = "NONE",
    MainDatabase = "NONE"
};
Preferences prefs = foo.Preferences.Add(newPrefs);

which then tries to create the database and fails when adding the primary key with the error

"BLOB/TEXT column 'StationName' used in key specification without a key length"

because it uses the data type "mediumtext" instead of CHAR or VARCHAR and MySQL can't use that type for a key.

Is there a method that is still more-or-less database agnostic that will tell MySQL to use the preferred type for the key column? Or do I just have to give up and make an integer key?

I also tried variations of the design like this but nothing worked.

class Preferences
{
    [Key,DataType("CHAR"),StringLength(30)]
    public string StationName { get; set; }
    [MaxLength(30)]
    public string MainDatabase { get; set; }
    [MaxLength(30)]
    public string DefaultSequence { get; set; }
}

Thanks for your help.

4

2 回答 2

5

尝试流畅的映射列类型可能:

modelBuilder.Entity<Preferences>()
    .Property(p => p.Id)
    .HasColumnType("CHAR(30)");

我认为这是等效的,[Column(TypeName = "CHAR(30)")]但不确定是否相同。

编辑:根据 Matt 的测试,长度是单独的,并且“char”可能区分大小写(MySQL 和其他与标识符区分大小写相关的设置有很多,操作系统有时可以发挥作用,因此可能会有所不同) :[Column(TypeName="char")][MaxLength(30)]

于 2013-03-21T21:06:35.443 回答
2

我建议您在关系数据库设计中应用一种普遍接受的做法,即使用无意义的主键。对业务领域毫无意义。

class Preferences
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    public int Id { get; set; }

    [MaxLength(30)]
    public string StationName { get; set; }
    [MaxLength(30)]
    public string MainDatabase { get; set; }
    [MaxLength(30)]
    public string DefaultSequence { get; set; }
}

额外的好处:现在您可以在必要时随意更改 StationName。

于 2013-03-21T20:47:08.593 回答