MVC - 种子GUID和表键

时间:2013-04-28 21:24:26

标签: c# asp.net-mvc asp.net-mvc-4 uniqueidentifier

在MVC中播种期间,如何防止在数据库中生成GUID?

这是我的班级:

[Table("Languages")]
public class Language
{
    [Key]
    public Guid ID { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 0)]
    public string Name { get; set; }

    [Required]
    [StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 0)]
    public string Code { get; set; }

    [DefaultValue(true)]
    public bool IsEnabled { get; set; }
}

这是我的种子方法:

protected override void Seed(SunLite.Models.SunLiteDBContext context)
{
    public static SunLiteDBContext Run(SunLiteDBContext context)
    {
        context.Languages.AddOrUpdate
        (
            x => x.ID,
            new Language { Name = "English", Code = "en-gb", ID = Guid.Parse("{fab5422a-f63d-4042-b7b1-705f69854bc9}"), IsEnabled = true },
            new Language { Name = "Spanish", Code = "es", ID = Guid.Parse("{24380e18-02bf-4668-87ee-b2514d17f384} "), IsEnabled = true },
            new Language { Name = "German", Code = "de", ID = Guid.Parse("{2c05c682-704f-43a4-864b-742ae359aa30}"), IsEnabled = true },
            new Language { Name = "French", Code = "fr", ID = Guid.Parse("{bf929fe3-67a0-425c-81d2-1ef554affc7c} "), IsEnabled = true },
            new Language { Name = "Turkish", Code = "tr", ID = Guid.Parse("{9d09cb45-3d0d-4238-a903-96c4f17481a1} "), IsEnabled = true }
       );
    }
}

目前,每次使用新guid将数据添加到数据库时,而不是我指定的数据。

1 个答案:

答案 0 :(得分:1)

您可以将属性[DatabaseGenerated(DatabaseGeneratedOption.None)]添加到ID媒体资源中。它应该有所帮助。