简体   繁体   English

ASP.NET MVC 5和实体框架多对多关系

[英]ASP.NET MVC 5 & Entity Framework many to many relationship

I have a many-to-many relationship between User and Task model. 我在User模型和Task模型之间存在多对多关系。 I want to assign tasks to users when I am creating a new task. 我要在创建新任务时将任务分配给用户。 Because of that I created UserViewModel and CheckBoxView model. 因此,我创建了UserViewModelCheckBoxView模型。 But now I can just assign tasks to users when I am editing a user table. 但是现在我可以在编辑用户表时将任务分配给用户。 I know I have to change UserController 's Create action but I do not know how. 我知道我必须更改UserControllerCreate操作,但是我不知道如何。

Here is my code: 这是我的代码:

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; }
}

User 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);
    }   
}

Edit 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>
}

You do not need the UserToTask class. 您不需要UserToTask类。 The relationships between them should be with the object classes themselves. 它们之间的关系应该与对象类本身有关。

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; }
}

You add in the TaskId as foreign key in the User class. 您将TaskId作为外键添加到User类中。 Each User will have a collection of Tasks (which may or may not be empty - so be careful with your constructors). 每个用户都将有一个Tasks集合(可能为空,也可能不为空-请谨慎使用构造函数)。

To find all the Users for a particular Task - you use a database query on Users -> where TaskId == Task.Id. 要查找特定任务的所有用户,请在用户->上使用数据库查询,其中TaskId ==Task.Id。

You'll need to sort out the xaml, controllers, etc, to fit the new model. 您需要对xaml,控制器等进行分类,以适应新模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.net MVC实体框架更新多对多关系 - ASP.net MVC Entity framework update Many to Many relationship ASP.NET MVC-实体框架多对多关系,插入数据 - Asp .NET MVC - Entity Framework many to many relationship, insert data 实体FrameWork使用Asp.Net的多对多关系 - Entity FrameWork Many to Many relationship using Asp.Net ASP.NET MVC3和实体框架 - 一个视图中的一对多关系 - ASP.NET MVC3 and Entity Framework- one-to-many relationship in one view ASP .NET Core MVC Entity Framework - 如何访问由多对多关系产生的表? - ASP .NET Core MVC Entity Framework - How to get access to a table which is result of many-to-many relationship? ASP .NET 核心 MVC 实体框架 - 将数据添加到多对多关系中 - ASP .NET Core MVC Entity Framework - add data into many-to-many relationship 使用Asp.net Boilerplate在Entity Framework中进行多对多关系复制记录 - Duplicating record in Entity Framework many to many relationship using Asp.net Boilerplate 使用 ASP.NET Core 和 Entity Framework Core 不会保存对 ICollection(多对多关系)的更改 - Changes to ICollection (many to many relationship) are not saved using ASP.NET Core and Entity Framework Core 使用EF 5和ASP.NET MVC 4为多对多关系添加值 - Add value to Many to Many relationship with EF 5 & ASP.NET MVC 4 CheckBoxList用于ASP.NET MVC中的多对多关系 - CheckBoxList for many-to-many relationship in ASP.NET MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM