所以这是问题here
的延续我正在尝试以下内容:
public DbSet<User> Users { get; set; }
public DbSet<Sport> Sports { get; set; }
public DbSet<Team> Teams { get; set; }
运动
public int ID { get; set; }
public List<Team> Teams { get; set; }
团队
public Team(int ID, int SportID, int Wins, int Losses, String Name, String Description, double Reputation, List<User> Members, byte[] TeamLogo)
{
this.ID = ID;
this.SportID = SportID;
this.Wins = Wins;
this.Losses = Losses;
this.Name = Name;
this.Description = Description;
this.Reputation = Reputation;
this.Members = Members;
this.TeamLogo = TeamLogo;
}
public int ID { get; set; }
public List<User> Members { get; set; }
public int SportID { get; set; }
用户
public int UserID { get; set; }
public List<Team> Teams { get; set; }
DB
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Adds middle table between Users and Teams
modelBuilder.Entity<User>()
.HasMany<Team>(t => t.Teams)
.WithMany(m => m.Members)
.Map(w => w.ToTable("UserTeam")
.MapLeftKey("UserID")
.MapRightKey("TeamID"));
}
public void addTeam(Team team, String sport)
{
// Add the team to the correct sport
Teams.Add(team);
this.SaveChanges();
}
控制器
model.NewTeam = new Team(0, db.getSportID(model.SelectedSport), 0, 0, model.TeamName, model.TeamDescription,
100, new List<User>() { model.currentUser }, model.ActualImage);
db.addTeam(model.NewTeam, model.SelectedSport);
问题:
它为Teams表添加了一条记录。它将记录添加到UserTeam表中就好了。问题是它还在User表中添加了一条新记录,因此我在User表中重复了用户。此外,当我查询Teams Table时,我得到一个空列表成员,因此EF不能从Many-Many表中正确地获取每个团队的成员。
答案 0 :(得分:0)
此问题来自此代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When :
<select id="action" name="action">
<option value="link">Link Clicked</option>
<option value="form">Form Submitted</option>
</select>
with:
<select id="action-attribute" name="action-attribute">
<option>ID</option>
<option>Class</option>
</select>
行public void addTeam(Team team, String sport)
{
// Add the team to the correct sport
Teams.Add(team);
this.SaveChanges();
}
将浏览Teams.Add(team)
实例,所有导航属性,每个导航集合中的每个项目,并将其标记为有新条目。这意味着每个条目的状态均为team
。然后,当您调用EntityState.Added
时,它将为数据库中为this.SaveChanges()
状态的每个条目创建新行。
要解决您的问题,您需要确保用于保存数据的上下文与用于检索您在以下列表中使用的项目相同EntityState.Added
如果您的上下文不相同,那么在new List<User>() { model.currentUser }
方法上您需要更改每个addTeam
的状态并将其标记为User
,以便上下文不会添加它们像这样新创建的条目:
EntityState.Unchanged