gpt4 book ai didi

c# - ASP.NET MVC 5 & Entity Framework 多对多关系

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:37 24 4
gpt4 key购买 nike

UserTask 模型之间存在多对多关系。我想在创建新任务时将任务分配给用户。因此,我创建了 UserViewModelCheckBoxView 模型。但是现在我可以在编辑用户表时将任务分配给用户。我知道我必须更改 UserControllerCreate 操作,但我不知道如何更改。

这是我的代码:

public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }

public virtual ICollection<UserToTask> UserToTasks { get; set; }
}

public class Task
{
public int Id { get; set; }
public string Title { get; set; }

public virtual ICollection<UserToTask> UserToTasks { get; set; }
}

public class UserToTask
{
public int Id { get; set; }
public int UserId { get; set; }
public int TaskId { get; set; }

public virtual User User { get; set; }
public virtual Task Task { get; set; }
}

public class CheckBoxViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}

public class UserViewModel
{
public int UserId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<CheckBoxViewModel> Tasks { get; set; }
}

用户 Controller :

public class UsersController : Controller
{
private MyModel db = new MyModel();

// GET: Users
public ActionResult Index()
{
return View(db.Users.ToList());
}

// GET: Users/Create
public ActionResult Create()
{
return View();
}

// POST: Users/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Surname")] User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(user);
}

// GET: Users/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

User user = db.Users.Find(id);

if (user == null)
{
return HttpNotFound();
}

var result = from a in db.Tasks
select new
{
a.Id,
a.Title,
Checked = (from ab in db.UserToTasks
where (ab.UserId == id) & (ab.TaskId == a.Id)
select ab).Any()
};

var MyViewModel = new UserViewModel();
MyViewModel.UserId = id.Value;
MyViewModel.Name = user.Name;
MyViewModel.Surname = user.Surname;

var MyCheckBoxList = new List<CheckBoxViewModel>();

foreach (var item in result)
{
MyCheckBoxList.Add(new CheckBoxViewModel{Id = item.Id, Name = item.Title, Checked = item.Checked});
}

MyViewModel.Tasks = MyCheckBoxList;

return View(MyViewModel);
}

// POST: Users/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserViewModel user)
{
if (ModelState.IsValid)
{
var MyUser = db.Users.Find(user.UserId);
MyUser.Name = user.Name;
MyUser.Surname = user.Surname;

foreach (var item in db.UserToTasks)
{
if (item.UserId == user.UserId)
{
db.Entry(item).State = EntityState.Deleted;
}
}

foreach (var item in user.Tasks)
{
if (item.Checked)
{
db.UserToTasks.Add(new UserToTask() {UserId = user.UserId, TaskId = item.Id});
}
}

db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
}

编辑 View :

@model ItalianCoach.Models.UserViewModel

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>User</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.UserId)

<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Tasks, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@for (int i = 0; i < Model.Tasks.Count(); i++)
{
@Html.EditorFor(m => m.Tasks[i].Checked)
@Html.DisplayFor(m => m.Tasks[i].Name)<br/>

@Html.HiddenFor(m => m.Tasks[i].Name)
@Html.HiddenFor(m => m.Tasks[i].Id)
}
</div>
</div>
</div>
}

最佳答案

您不需要 UserToTask 类。它们之间的关系应该与对象类本身有关。

public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }

public int TaskId { get; set; }
public virtual Task Task { get; set; }

public virtual ICollection<Task> Tasks { get; set; }
}

public class Task
{
public int Id { get; set; }
public string Title { get; set; }
}

您将 TaskId 作为外键添加到 User 类中。每个 User 都有一个 Tasks 集合(可能为空也可能不为空 - 所以要小心你的构造函数)。

要查找特定任务的所有用户 - 您对用户使用数据库查询 -> 其中 TaskId == Task.Id。

您需要整理 xaml、 Controller 等以适应新模型。

关于c# - ASP.NET MVC 5 & Entity Framework 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45387242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com