eestein
eestein

Reputation: 5114

How to add two different properties of the same class to one POCO class?

I have a class that has two references to one class (User):

public class Xpto {
    public string Username { get; set; }
    public virtual User User { get; set; }
    public string Username2 { get; set; }
    public virtual User User2 { get; set; }
}

The thing is EF only creates references to the first key (Username). That way User and User2 have Username as key and not what I intended...

I found this to be the answer:

nHibernate, mapping two properties to the same class

But I wouldn't know how to apply this to my scenario.

Thanks.

EDIT: Folks, nevermind... I guess I should've looked a little further. The answer is here: How do I create a POCO object that has 2 references to another class

The standard is <property_name><key_name> So the correct way would be UserUsername and User2Username

Thanks.

Upvotes: 0

Views: 166

Answers (1)

Daniel Persson
Daniel Persson

Reputation: 2233

Consider using the ForeignKeyAttribute instead, then you can select the names you like for your key attributes.

public class Xpto {

    [ForeignKey("User")]
    public string Username { get; set; }

    public virtual User User { get; set; }

    [ForeignKey("User2")]
    public string Username2 { get; set; }

    public virtual User User2 { get; set; }
}

Upvotes: 1

Related Questions