Shido
Shido

Reputation: 35

How to get name from another table with Id MVC 5?

I have an hard time trying to understand how to get a name from another table by using an foreign key in my MVC 5 project. I'm wanting to have a one to many relationship with my ShirtSize and Products table, so one size has many Products.

I have this setup on my product model

    public int Id { get; set; }
    public string Name { get; set; }

    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    public string Description { get; set; }


    [Display(Name = "Size")]
    public int SizeId { get; set; }
    public virtual ShirtSize ShirtSize { get; set; }

    [Display(Name = "Image Name")]
    public string ImageFileName { get; set; }

And this is what I have for my ShirtSize model

        public int Id { get; set; }
        public string Size { get; set; }
        public virtual ICollection<Product> Products { get; set; } 

Size property is the name of the sizes like large medium, or small. Now how do I get the Size by using the ShirtId from the products table?

I tried to do something similar to the code below but inside the Include part highlights red.

public ViewResult Index()
{
    var courses = db.Courses.Include(c => c.Department);
    return View(courses.ToList());
}

Upvotes: 2

Views: 5982

Answers (2)

jimSampica
jimSampica

Reputation: 12410

By the way you described this would be the approach...

var sizeId = 2;
var product = db.Products.FirstOrDefault(p => p.SizeId == sizeId);
var size = product.ShirtSize.Size;

However, if you think about it you could get back a different product each time FirstOrDefault is called (or possibly nothing at all). If you wrote code that used that product you may inadvertantly introduce a bug into your app. A safer way would be to just get the size directly from the ShirtSizes table. This way there is no doubt what your intentions are. You can write that in this way...

var sizeId = 2;
var shirtSize = db.ShirtSizes.FirstOrDefault(s => s.SizeId == sizeId);
var size = shirtSize.Size;

Upvotes: 3

Ankush Jain
Ankush Jain

Reputation: 6999

try the following

var shirtId = 2;
var product = db.Products.FirstOrDefault(p => p.Id== shirtId);

Here you have got product ( shirt) object Now you can find size by the following

product.ShirtSize.Size

Upvotes: 0

Related Questions