简体   繁体   中英

EntityFramework many to many realation in project MVC

I have a three table TaskModels, TaskAssigned and Users(AspNetUsers). With Task TaskModels i am creating new tasks and with Task Assigned model i assign this tasks to Users. Everything is working but as i post in the image i just get users id and tasks id witch assigned to the user. But i want to see User name Task name instead of their id. Here is my code and result img.

public class TaskAssigned
{
    public int Id { get; set; }
    public int TaskModelId { get; set; }
    public int UserId { get; set; }
    public TasksModel TasksModel { get; set; }
    public ApplicationUser User { get; set; }
}


public class TasksModel
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Heading is required")]
    public string Heading { get; set; }

    [Required(ErrorMessage = "Content is required")]
    public string Content { get; set; }

    [Required(ErrorMessage = "Start Date is required")]
    [DisplayName(displayName: "Start Date")]
    public DateTime StartDate { get; set; }

    [Required(ErrorMessage = "Deadline is required")]
    [DisplayName(displayName: "Deadline")]
    public int DeadlineTask { get; set; }          
}

public class ApplicationUser 
{
    public string Name { get; set; }
    public List<TaskAssigned> TaskAssigneds { get; set; }
}

Here is my TaskAssignedsController

public class TaskAssignedsController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: TaskAssigneds
    public ActionResult Index()
    {
        var list = db.TaskAssigneds.Include(o => o.TasksModel).Include(o => o.User);

        return View(list.ToList());
    }

    // GET: TaskAssigneds/Create
    public ActionResult Create()
    {            
        ViewBag.TaskModelId = new SelectList(db.TasksModels,"Id", "Heading");
        ViewBag.UserId = new SelectList(db.Users, "ApplicationUserId", "UserName");
        return View();
    }

    // POST: TaskAssigneds/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,TaskModelId,UserId")] TaskAssigned taskAssigned)
    {
        if (ModelState.IsValid)
        {
            db.TaskAssigneds.Add(taskAssigned);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.TaskModelId = new SelectList(db.TasksModels, "Id", "Heading", taskAssigned.TasksModel.Heading);
        ViewBag.UserId = new SelectList(db.Users, "ApplicationUserId", "UserName", taskAssigned.User.UserName);

        return View(taskAssigned);
    }  

TaskAssigneds index view

And my result

The easier way (not recommended) of solving it is to instead of using this:

@Html.DisplayFor(modelItem => item.TaskModelId)

@Html.DisplayFor(modelItem => item.UserId)

use this:

@Html.DisplayFor(modelItem => item.TasksModel.Name)

@Html.DisplayFor(modelItem => item.User.Name)

However, it looks your TasksModel doesn't have a name property. Also, you should fix @Html.DisplayNameFor as well (for both columns).


Now, what I recommend is creating a View Model like this:

public class TasksAssignedViewModel
{
    public int TaskModelId { get; set; }
    public int UserId { get; set; }
    public int TaskModelName { get; set; }
    public int UserName { get; set; }
}

..then in your Index action, project your query into that View Model like this:

public ActionResult Index()
{
    var list = db.TaskAssigneds.Select(l => new TasksAssignedViewModel
        {
            TaskModelId = l.TasksModel.Id,
            UserId = l.User.Id,
            TaskModelName = l.TasksModel.Name,
            UserName = l.User.Name
        });
    return View(list.ToList());
}

...finally in your Index.cshtml , you edit the type of your model:

@model IEnumerable<DeadLiner.Models.TasksAssignedViewModel>

With this, there is no need to use Include anymore. This also makes the query a bit faster, since you are not fetching all fields from database anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM