Brian D
Brian D

Reputation: 10163

Using foreign key relationships in Views entity

Is it possible to step through a model's foreign key to access another model in a View? I want to return one type of model to my view, but get the data from another model. For example, in my view:

@[ModelObject].[Field (ForeignKey)].[ForeignKey Field]

Edit:

Your feedback has been helpful so far, and it sounds like a View Model might be the way to go, but allow me to provide a little more information so that you can better advise.

I have an x.Id, and I want to find all Y objects that are associated with x.Id -- this mapping is held in a table XYMap where several Y.Ids map to one X.Id. Both of these models are in the same entity:

public class X
{
    [Key]
    public int xId {get; set;}
}

public class XYMap
{
    [Key, ForeignKey("Y")]
    public int yId { get; set; }

    [ForeignKey("X")]
    public int xId { get; set; }
}

public class Y
{
    [Key]
    public int yId { get; set; }
}

What I have tried to do is, given an x.Id called someXid:

var yIdList = db.XYMap.Where(item => item.xId == someXid).ToList()

I want to get all of the Y objects so I can display their data in the view.

Upvotes: 0

Views: 102

Answers (1)

amhed
amhed

Reputation: 3659

It's possible, but not recommended. Perhaps the navigational property is setup with lazy loading and calling @Model.NavigationalField from the view results in a call to the database. The view shouldn't be responsible for these kind of calls.

I would recommend creating a ViewModel that combines the properties that you need from both entities.

Upvotes: 1

Related Questions