ef6种子数据与关系

时间:2016-08-02 07:13:47

标签: c# entity-framework

我有两种模式:

  public class Language
  {
    [Key]
    [Required]
    [MaxLength(2), MinLength(2)]
    public string Code { get; set; }
    [Required]
    public string Country { get; set; }
  }

和另一个

  public class Text
  {

    private string _fieldname;

    public int Id { get; set; }
    [Required]
    public virtual Language Language { get; set; }

    [Required]
    [MinLength(1)]
    [MaxLength(30)]
    public string Fieldname {
      get { return _fieldname; }
      set { _fieldname = value.ToUpper(); }
    }

    [MaxLength(50)]
    [MinLength(1)]
    [Required]
    public string Description { get; set; }
  }

现在我想用数据为数据库播种并尝试:

context.Language.AddOrUpdate(
        new Language[]
        {
          new Language() { Code = "AF", Country = "Afghanistan" },
          new Language() { Code = "AX", Country = "Aland Islands" },
          new Language() { Code = "AL", Country = "Albania" },
          new Language() { Code = "DZ", Country = "Algeria" },
          new Language() { Code = "AS", Country = "American Samoa" },
          new Language() { Code = "AD", Country = "Andorra" },
          new Language() { Code = "AO", Country = "Angola" },
          new Language() { Code = "AI", Country = "Anguilla" },
          new Language() { Code = "AQ", Country = "Antarctica" },
          new Language() { Code = "AG", Country = "Antigua and Barbuda" },
          new Language() { Code = "AR", Country = "Argentina" },
          new Language() { Code = "AM", Country = "Armenia" },
          .......

我的问题是,我不知道如何在Language字段

上播种文字
   context.Text.AddOrUpdate(
        new Text[]
        {
          new Text() {Fieldname = "SERVER", Description = "Server", Language = }, 
        }
        );

1 个答案:

答案 0 :(得分:2)

通过查询上下文中现有的语言,您的代码可能如下所示。

context.Text.AddOrUpdate(
    new Text[]
    {
      new Text() {
        Fieldname = "SERVER",
        Description = "Server", 
        Language = context.Language.Where(l => l.Code == "AX").FirstOrDefault()
        }, 
        //More new Text() here...
    }
);