如何设置代码第一个实体

时间:2013-10-17 09:55:12

标签: c# entity-framework ef-code-first code-first

我正在努力解决代码优先实体和数据注释的概念。

我正在尝试创建一个数据库,其中包含一个People表和一个由一对多关系链接的集合表,因为在每个集合中可以有很多人。

我究竟如何设置这些类来模拟一对多关系,更重要的是如何将数据添加到每个表中。

我尝试了以下内容:

//Ensemble entity class
public class Ensemble
{
    [Key]
    public int ensembleID { get; set; }
    public string ensembleName { get; set; }

    public virtual List<People> persons { get; set; }

    public Ensemble (int ensembleID, string ensembleName)
    {
        this.ensembleID = ensembleID;
        this.ensembleName = ensembleName;
    }
}

// people entity class
    public class People
{
    [Key]
    public int personID { get; set; }
    [Required]
    public string firstname { get; set; }
    [Required]
    public string surname { get; set; }
    [Required]
    public DateTime birthDate { get; set; }
    public string cellphone { get; set; }
    public string email { get; set; }
    public bool inSchool { get; set; }  //  Are they currently in a primary or secondary school

    public int ensembleID { get; set; }
    //[ForeignKey("ensembleID")]
    public Ensemble Ensemble { get; set; }


    public People(int personID, string firstname, string surname, DateTime birthDate, string cellphone, string email, bool inSchool, int ensembleID)
    {
        this.personID = personID;
        this.firstname = firstname;
        this.surname = surname;
        this.birthDate = birthDate;
        this.cellphone = cellphone;
        this.email = email;
        this.inSchool = inSchool;
        this.ensembleID = ensembleID;
    }


    // Adding data
    context.People.Add(new People(1, "Adam", "Herd", new DateTime(1992, 3, 12), "0274578956", "adamherd1@live.com", true));
    context.Ensemble.Add(new Ensemble(1, "Little River Band"));

然而,这会返回错误。 'INSERT语句与FOREIGN KEY约束冲突\“FK_dbo.People_dbo.Ensembles_ensembleID \”。冲突发生在数据库\“SMMC_adam_stacy.Context \”,table \“dbo.Ensembles \”,列'ensembleID'。\ r \ n语句已终止。“}'

如何正确地执行此操作的代码片段将被强制执行,因为这将有助于解释导航属性如何工作,例如公共虚拟集合集合{get;组; }

2 个答案:

答案 0 :(得分:0)

context.Ensemble.Add(new Ensemble(1, "Little River Band"));
context.People.Add(new People(1, "Adam", "Herd", new DateTime(1992, 3, 12), "0274578956", "adamherd1@live.com", true));

答案 1 :(得分:0)

将人员添加到Ensemble中的收藏集:

var ens = new Ensemble(1, "Little River Band");
var person = new People(1, "Adam", "Herd", new DateTime(1992, 3, 12),
                        "0274578956", "adamherd1@live.com", true)); 
                        // BTW: the constructor does not match the call
ens.persons.Add(person);
context.Ensemble.Add(ens);