我如何播种具有外键的 table,该外键在模型中指定为对象,但在 table 中指定为 guid

How do i seed a table that has a foreign key, which is specified as an object in the model, but as a guid in the table

所以我对 Entity Framework 6 及其代码优先实现有疑问。在创建两个 table 时,我将一个设置为具有一个外键,该外键是另一个的 id (guid)。我通过将 table 的属性之一设为对象类型(如代码中所示)来实现这一点。当我打开数据库资源管理器时,该列显示为一个字符串,代表一个 id(我猜 EF 自己弄清楚了这种关系)。但是,当我尝试为第二个 table 播种并向第二个外键提供第一个 table 的模型实例时,我收到一条错误消息 "Unable to create a constant value of type 'cq.Models.SurveyTemplate'. Only primitive types or enumeration types are supported in this context."。当我尝试添加一个字符串(父 table 的 guid)时,我得到一个错误,该模型需要 SurveyTemplate 类型的 属性,而不是文字字符串。我可以让 属性 只是模型中的一个字符串,但我把它设置为一个模型,让 EF 做它的关系不就是这个想法吗?提前感谢您的帮助:) 此外,自动迁移设置为 true

这是种子方法

protected override void Seed(cq.Models.ApplicationDbContext context) {
    SurveyTemplate surveyTemplate = context.SurveyTemplates.Find(
    "d87ab2a8-4eb4-4272-b7e4-afe2f8999b4e");
    context.QuestionTemplates.AddOrUpdate(q => new { 
        q.Text, q.SurveyTemplate 
    }, new QuestionTemplate {
        Id = Guid.NewGuid().ToString(),
        Text = "What is your contact info?",
        Type = "Contact Info",
        SurveyTemplate = surveyTemplate
    });
}

这是 SurveyTemplate 模型

    public class SurveyTemplate {
        public string Id { get; set; }
        public string Name { get; set; }
    }

这是问题模板模型

    public class QuestionTemplate {
        public string Id { get; set; }
        public string Text { get; set; }
        public string Type { get; set; }
        public SurveyTemplate SurveyTemplate { get; set; }
    }

好吧,对于以后遇到这个问题的人,我想我找到了问题的解决方案,因为我对 ASP.NET MVC 还很陌生。在创建QuestionTemplate模型时,不仅需要创建public SurveyTemplate SurveyTemplate { get; set; },还需要指定一个public string SurveyTemplateId { get; set; },并在SurveyTemplate[=]之前放置一个[ForeignKey("SurveyTemplateId")]注解23=],以便框架了解您在添加或播种时尝试做什么。这是我的种子方法和模型:

protected override void Seed(cq.Models.ApplicationDbContext context) {
    SurveyTemplate surveyTemplate = context.SurveyTemplates.Find("d87ab2a8-4eb4-4272-b7e4-afe2f8999b4e");
    if (!context.QuestionTemplates.Any(q => q.Text == questionTemplate.Text && q.SurveyTemplate.Id == questionTemplate.SurveyTemplate.Id)) {
        context.QuestionTemplates.Add(new QuestionTemplate {
            Id = Guid.NewGuid().ToString(),
            Text = "What is your contact info?",
            Type = "Contact Info",
            SurveyTemplate = surveyTemplate
        });

        context.SaveChanges();
    }
}
public class QuestionTemplate {
    public string Id { get; set; }
    public string Text { get; set; }
    public string Type { get; set; }
    public string SurveyTemplateId { get; set; }

    [ForeignKey("SurveyTemplateId")]
    public SurveyTemplate SurveyTemplate { get; set; }
}

我希望我帮助了别人!

编辑:由于显然 AddOrUpdate 非常不可靠,我将其切换,您应该在代码中看到它。干杯!