我有2个表学生和主题他们有很多2个很多的关系: -
我的表结构是: -
如何从mvc控制器
在这些表中插入数据这是studentmaster.cs
public partial class studentmaster
{
public studentmaster()
{
this.subjects = new HashSet<subject>();
}
public int studentid { get; set; }
public string studentname { get; set; }
public Nullable<System.DateTime> dob { get; set; }
public Nullable<int> registrationnumber { get; set; }
public virtual ICollection<subject> subjects { get; set; }
}
这是subject.cs
使用System; 使用System.Collections.Generic;
public partial class subject
{
public subject()
{
this.studentmasters = new HashSet<studentmaster>();
}
public int subjectid { get; set; }
public string subjectname { get; set; }
public virtual ICollection<studentmaster> studentmasters { get; set; }
}
这个Model3.context.cs
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class studentEntities : DbContext
{
public studentEntities() : base("name=studentEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<studentmaster> studentmasters { get; set; }
public DbSet<subject> subjects { get; set; }
public DbSet<sysdiagram> sysdiagrams { get; set; }
}
答案 0 :(得分:0)
它应该类似于:
var subject = context.subjects.First(); //just an example of getting the subject
var student = context.students.Find(id); //get the student you want to update
student.subjects.Add(subject);
context.SaveChanges();
return View();
如果我错过了一些细微差别并且这不起作用,我会在星期一编辑我的帖子,当时我的源代码就在我面前。
当你没有向我们展示你以前的尝试时,我们很难知道你做错了什么。保存错误总是更好,直到你做对,而不是立即删除它们。