开发者

Using VB.NET MVC3 and the Entity Framework "Code-First" method, how can I easily define multiple one-to-many relationships with the same model?

I'm very new to ASP.NET and could use some help.

For this scenario, I have 2 classes. One is a "project" class and the other is a "company" class. Essentially, what I need is one single "company directory" of all the companies we have relationships with, but I need to be able to freely slot them into 3 different slots within a project. It is possible that the same company could occupy all 3 slots, but it's equally likely that a different company will be placed in each slot.

Here are my classes:


public class Project
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ClientID { get; set; }
    public int PublisherID { get; set; }
    public int DeveloperID { get; set; }

    public Company Client { get; set; }
    public Company Publisher { get; set; }
    public Company Developer { get; set; }
}

public class Company
{
    public int ID { get; set; }
    public string Name { get; set; }
}

When I have used this basic outline in the past, the complex types I specify in the bottom half of the model definition will be auto generated based on the matching int ID properties specified earlier. For example, If I had a complex type "User" that was drawing it's data from a user table in my database, specifying (int UserID) within my class followed by (User User), the UserID field would be the actual field in my project table and the User object I specify will automatically be an object containing all the User information from the user table.

Using this method as I did in the classes specified above, however, does not work in the way I expected and instead creates not only ClientID, PublisherID, and DeveloperID but also creates CompanyID, CompanyID1, and CompanyID2 which are the fields that will actually be used when attempting to instantiate the Company objects I specified (even though those fields will contain开发者_运维技巧 null always).

Is there any way around this?


You just need to specify that your int properties are the foreign keys to your navigation properties.

public class Project
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ClientID { get; set; }
    public int PublisherID { get; set; }
    public int DeveloperID { get; set; }

    [ForeignKey("ClientID")]
    public Company Client { get; set; }

    [ForeignKey("PublisherID")]
    public Company Publisher { get; set; }

    [ForeignKey("DeveloperID")]
    public Company Developer { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜