1

I am just getting into MVC 4 and Entity Framework 5 and want to know if what I am doing is correct?

I have a UserObject and a JobObject, the jobObject has a reference to a User Object.

public class Job
{
    public int id { get; set; }
    public virtual MyUser User { get; set; }
    public JobType JobType { get; set; }
}

When I want to create an instance of the Job I am passing in the query string a parameter UserID, but the Job only deals with an instance of MyUser.

Is the following the correct way to associate the user to the job?

[HttpPost]
public ActionResult Create(Job job, int userid)
{
   if (ModelState.IsValid)
   {    
     MyUser staffmember = db.MyUsers.Find(userid);
     if (staffmember == null)
      {
        return View("StaffMemberNotFound");
      }
     job.User = staffmember;
     db.Jobs.Add(job);
     db.SaveChanges(); 
   }
}

Or is there a better way to associate the user to the job?

2 Answers 2

1

Your way will work but I prefer to simply work with ids if possible.

What I would suggest is that you add a MyUserId property to your Job class (remember to update the database if you are using codefirst):

public class Job
{
    public int id { get; set; }
    [ForeignKey("User")]
    public int MyUserId { get; set: }

    public virtual MyUser User { get; set; }
    public JobType JobType { get; set; }
}

Then simply populate the MyUserId. You can also change your check to simply check if the id exists as apposed to finding an object and letting EF map that to a class before returning it to you

[HttpPost]
public ActionResult Create(Job job, int userid)
{
   if (ModelState.IsValid)
   {    
     if (!db.MyUsers.Any(u => u.Id == userid)
     {
        return View("StaffMemberNotFound");
     }

     job.MyUserId = userid;
     db.Jobs.Add(job);
     db.SaveChanges(); 
   }
}

EF will do the rest of the mapping for you when you next retrieve the record from the database.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried what you suggested (I also deleted the DB so as to start out with a clean DB) but I have one of two issues. If I add MyUserId then I end up in the DB with two different IDs ie two fields. MyUserID and MyUser_ID (Entity framework generated id for the user) and my redundant MyUserId If I create a field called MyUser_ID I get an error about creating two fields with the same name? What am I doing wrong?
My apologies, I thought ef convention would have picked this up. On your MyUserId property add [ForeignKey("MyUser")]. I'll update my answer
UPDATE: Use [ForeignKey("User")] above, not [ForeignKey("MyUser")] as previously stated. My answer is now up to date
0

Your approach works fine, the only small optmization you could make is not taking the "retrieval hit" of MyUser staffmember = db.MyUsers.Find(userid); since you already have the userid.

I am using ASP.NET MVC 4 and Entity Framework 5.0, and here is my code (different model objects, but same intent as what you are doing).

Note: I let EF generate my model classes by right-clicking on the Models folder and choosing Add->ADO.NET Entity Data Model in VS.NET 2012.

Store.Models.Product

namespace Store.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Product
    {
        public long Id { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public System.DateTime DateAdded { get; set; }
        public Nullable<long> CategoryId { get; set; }

        public virtual Category Category { get; set; }
    }
}

Store.Models.Category

namespace Store.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Category
    {
        public Category()
        {
            this.Products = new HashSet<Product>();
        }

        public long Id { get; set; }
        public string CategoryName { get; set; }
        public System.DateTime DateAdded { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }
}

On my Create.cshtml page, I have the User select the CategoryId from the drop-down list. This Category Id is bound to Product.CategoryId. All I do in my method is this:

ProductController

public class ProductController : Controller
{
    ...
    [HttpPost]
    public ActionResult Create(Product product)
    {
        product.DateAdded = DateTime.Now;
        if (dbContext != null)
        {
            dbContext.Products.Add(product);
            dbContext.SaveChanges();
        }
        return RedirectToAction("Index");
    }
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.