Bill Software Engineer
Bill Software Engineer

Reputation: 7782

In MVC modeling, how do I bind a property to another model?

So I have 2 models, where Model2 is linked to Model1:

public class Model1 {
    public int model1ID { get; set; }
    public int model2ID { get; set; }
}
public class Model2 {
    public int model2ID { get; set; }
    public int someData { get; set; }
}

I would like to do this:

public class Model1 {
    public int model1ID { get; set; }
    public Model2 model2 { get; set; }
}

So I can do this:

        var linqTest = (
            from curTest in database.Model1s
            select curTest 
        ).Sum(curTest => curTest .model2.someData);

EDIT:

My problem is that how do I tell c# how to load the "model2" property using "model2ID"? The specific error I get is:

{"Invalid column name 'model1_ID'.\r\n Invalid column name 'model1_ID'."}

Notice that I don't have any property with the name model1_ID.

Upvotes: 0

Views: 368

Answers (1)

Steven Wexler
Steven Wexler

Reputation: 17279

It sounds like you want to use association properties:
Entity Framework association properties: http://msdn.microsoft.com/en-us/data/jj713564.aspx
Linq to SQL association properties: http://msdn.microsoft.com/en-us/library/bb629295.aspx

Your data model with association properties will look something like:

public class Model1 
{
    public int model1ID { get; set; }
    public int model2ID { get; set; }
    public virtual Model2 model2 { get; set; }
}

public class Model2
{
    public int model2ID { get; set; }
}

If you don't want to use association properties, you can use a join in your query:

var linqTest = (
            from mod1 in database.Model1s
            join mod2 in database.Model2s
                on mod1.model2ID equals mod2.model2ID
            select new { Mod1 = mod1, Mod2 = mod2 } 
        ).Sum(row => row.Mod2.someData);

Check the link @nercan posted for more information on joins in Linq queries

Upvotes: 1

Related Questions