創建的表我都定義爲如何插入數據加入其中,通過使用EF代碼第一次
1)項目類
public class Project
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProjectId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
public ICollection<Person> Persons { get; set; }
}
2)人兩個實體類類
public class Person
{
public Person()
{
Projects = new List<Project>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string Designation { get; set; }
public string CellPhone { get; set; }
public ICollection<Project> Projects { get; set; }
}
而在我的DataContext類中,配置定義爲
public class DataContext: DbContext
{
public DataContext()
: base("name=DataContext")
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<Person> Persons { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>()
.HasMany<Person>(p => p.Persons)
.WithMany(p => p.Projects)
.Map(m =>
{
m.ToTable("ProjectPersons");
m.MapLeftKey("ProjectId");
m.MapRightKey("PersonId");
});
}
}
我創造了新的項目後,項目表,表的人用它填充的紀錄,但我發現它是通過接合不與專案編號和PERSONID填充創建ProjectPerson表。
任何建議嗎?
這裏是我的HttpPost方法來創建新的項目
[HttpPost]
public ActionResult CreateProject(Projects newProject, int page = 1)
{
_ctx.Projects.AddProject(newProject, ref _ctx);
_ctx.Person.AddPerson(newProject.Person, newProject, ref _ctx);
_ctx.SaveChanges();
var userProjects = _ctx.Projects.GetStaffUserProjects(providerUserKey, page, ref _ctx);
return PartialView("_Projects", userProjects);
}
這裏是我的推廣方法, 'AddProject' 和 'addPerson的'
1)AddProject
public static void AddProject(this IEnumerable<Project> projects, Projects newProject, ref DataContext ctx)
{
var project = new Project
{
Title = newProject.Title,
Duration = newProject.Duration,
Description = newProject.Description,
CreatedDate = DateTime.Now,
Status = true,
UserId = (int)Membership.GetUser().ProviderUserKey,
ProjectCategoryId = newProject.SelectedProjectCategoryId,
OrganizationId = newProject.SelectedOrganizationId
};
ctx.Projects.Add(project);
}
2) addPerson的
public static void AddPerson(this IEnumerable<Person> persons, Person newPerson, Projects newProject, ref DataContext ctx)
{
var person = new Person
{
Name = newPerson.Name,
EmailAddress = newPerson.EmailAddress,
CellPhone = newPerson.CellPhone,
Designation = newPerson.Designation
};
ctx.Person.Add(person);
}
}
可有人請看看這個帖子? – user2866746
你能展示你的代碼:「*創建新項目*」嗎? – Slauma
沒有人讀您的評論,除非他們在看您的文章:) - 你可能從未添加項目要麼'Project.Persons'或'Person.Projects'。無論如何,正如Slauma說的那樣,請說明如何爲數據庫創建種子。 –