0

I have the query with a join

  var DetailsQuery = (from a in db.aTable
                                 join b in db.bTable on a.carID equals b.ID
                                 where a.ID==id
                                    select new
                                 {
                                     ID = a.ID != null ? a.ID : 0,
                                     aName= a.aName,
                                     carName= b.carName,
                                 }).Take(1);

Am I doing correct using Take(1)? There actually any way must be only one row with such ID, so should I write this Take(1) or It will work without it?

Now, I created a new model class for the view

public class ModifiedaTableModel
{
        [Key]
        [Required(ErrorMessage = "aIDis required.")]
        public int aID{ get; set; }
        [Required(ErrorMessage = "aName required.")]
        public string aName{ get; set; }
        [Required(ErrorMessage = "carName required.")]
        public string carName{ get; set; }
}

How can I transfer this query object to this model and so I can show it in view?

1
  • If you don't know for sure you can get whole result, check if it's more than one, log some error or whatever, then take .First(). Commented Oct 19, 2018 at 6:59

2 Answers 2

1
  var DetailsQuery = (from a in db.aTable
                                 join b in db.bTable on a.carID equals b.ID
                                 where a.ID==id
                                    select new
                                 {
                                     ID = a.ID != null ? a.ID : 0,
                                     aName= a.aName,
                                     carName= b.carName,
                                 }).FirstOrDefault();

For using the view model in the view:

@model <your project name>.ViewModels.ModifiedaTableModel;

Assume you have your view model class in "ViewModels" folder.

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

Comments

0

Controller:

var DetailsQuery = from a in db.aTable
                   join b in db.bTable on a.carID equals b.ID
                   where a.ID == id
                   select new ModifiedaTableModel
                   {
                       ID = a.ID != null 
                            ? a.ID 
                            : 0,
                       aName = a.aName,
                       carName = b.carName
                   });

return View(DetailsQuery.FirstOrDefault());

View (namespace of model may be required):

@model ModifiedaTableModel

If you select only anonymous type object, an InvalidOperationException might occur during view rendering.

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.