多对多的关系未能正确保持

时间:2017-07-13 10:04:01

标签: c# entity-framework entity-framework-6

请参阅下面的DDL:

create table Person (ID identity not null, varchar(name), primary key (id))
create table PersonSport (PersonID int not null references Person(ID), SportID int not null references Sport(ID))
create table Sport (ID identity int not null, description varchar(20), primary key(id))
insert into sport (description) values ('running') //ID =1 from auto increment
insert into sport (description) values ('football') //ID = 2 from auto increment

实体框架正确创建了两个类,即Person和Sport。然后我试试这个:

public int Create()
        {
            Person person = new Person();
        person.name = 'Bert';
             List<Sport> listSport = new List<Sport>;

            Sport sport = new Sport();
            sport.ID=1; //ID=1 is running
            Sport.Description='running';
            listSport.Add(sport);
            person.Sport = listSport;

            using (PersonSportEntities db = new PersonSportEntities())
            {
                db.Person.Add(person);
                db.SaveChanges();
            }
        }

此后运行;似乎实体框架已经这样做了:

1)INSERT INTO Sport (description) values ('running'); // ID = 3来自自动增量

2)插入人(姓名)值(&#39;伯特&#39;)

3)INSERT INTO PersonSport (1,3); //3 is the auto increment from step 1

我希望它能做到这一点:

1)插入人(姓名)值(&#39;伯特&#39;)

2)INSERT INTO PersonSport (1,2);

我做错了什么?

3 个答案:

答案 0 :(得分:3)

Add Person实例在上下文之前,只需Attach Sport个实例(因此告诉EF将它们视为现有实体,而不是新实体,就好像你没有那样做:

using (PersonSportEntities db = new PersonSportEntities())
{
    foreach (var sport in person.Sport)
        db.Sport.Attach(sport);
    db.PersonSport.Add(personSport);
    db.SaveChanges();
}

在这种情况下,除了Sport之外,您不需要指定Id个对象属性,因为它们是假的(也就是 stub )对象,只是为了创建链接。

答案 1 :(得分:0)

试试这种方式,

public int Create()
    {
        Person person = new Person();
        person.name = 'Bert';

        using (PersonSportEntities db = new PersonSportEntities())
        {   
            List<Sport> sport = db.Sport.Where(x => x.ID = 1).ToList();
            person.Sport = sport;

            db.Person.Add(person);
            db.SaveChanges();
        }
    }

答案 2 :(得分:-1)

我认为你必须有3个型号。 PersonPersonSportSport

public class PersonSport
{
   public int Id {get; set;} //key and auto increment
   public int PersonId {get; set} //foreign key
   public int SportId {get; set} // foreign key

// relationship
   public virtual Person Person {get; set;} 
   public virtual Sport Sport {get; set;} 
}

public int Create()
    {
        var personSport=new PersonSport();
        personSport.SportId=1; 
        personSport.Person=new Person()
        {
         Name="Bert"
        };
        using (PersonSportEntities db = new PersonSportEntities())
        {   
            db.PersonSport.Add(personSport);
            db.SaveChanges();
        }
    }