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.
Try fluent mapping column type maybe:
modelBuilder.Entity<Preferences>()
.Property(p => p.Id)
.HasColumnType("CHAR(30)");
I think this is equivilent of [Column(TypeName = "CHAR(30)")]
but not certain it's the same.
Edit: As per Matt's testing, length is seperate and, "char" may be case sensitive(there are a lot of settings in MySQL and other engiens related to case sensitivity in identifiers, and OS can play a part sometimes, so may vary): [Column(TypeName="char")][MaxLength(30)]
I would suggest you apply a commonly accepted practice in relational database design, which is to have meaningless primary keys. Meaningless to the business domain that is.
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; }
}
Additional benefit: now you're free to change the StationName whenever necessary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.