1

我正在为代码优先实体和数据注释的概念而苦苦挣扎。

我正在尝试创建一个数据库,其中包括一个 People 表和一个 ensemble 表,它们通过一对多的关系链接,因为在每个 ensemble 中可以有很多人。

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

我尝试了以下方法:

//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\"、表 \"dbo.Ensembles\"、列 'ensembleID' 中发生冲突。\r\n语句已终止。"}'

如何正确执行此操作的代码片段以及对导航属性如何工作的进一步解释,例如 public Virtual Ensemble Ensemble { get; 放; }

4

2 回答 2

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));
于 2013-10-17T10:07:56.640 回答
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);
于 2013-10-17T13:12:41.873 回答