AlegSilva
AlegSilva

Reputation: 1

Mapping FK relationships in EF codefirst

Let's say i have 2 tables like:

Table:User
-------------
- UserId [pk]
- UserName
- StatusId [fk]

Table: Status
-------------
- StatusId [pk]
- StatusDescription

Now let's say i want to show the StatusDescription in my poco like:

public class User
{
int UserId{get;set;}
string UserName{get;set;}
int StatusId{get;set;}
string StatusDescription{get;set;}
}

Is it possible to map this in EF? Or i can only achieve this with:

public class User
{
int UserId{get;set;}
string UserName{get;set;}
Status UserStatus{get;set;}
}

Any ideas? Thank's in advance.

Upvotes: 0

Views: 157

Answers (2)

Omer Cansizoglu
Omer Cansizoglu

Reputation: 1281

You can create an extension method to generate a POCO object with any complex properties.

  public static class UserExtensions
    {
        public static UserPoco ToPoco(this User user)
        {
            UserPoco poco = new UserPoco();
            poco.UserId = user.UserID;
            poco.UserName = user.UserName;
            poco StatusDescription = user.Status.StatusDescription;
            return poco;
        }
        public static UserPoco ToPoco(this User user,ExtraObjectToInclude object)
        {

            //....you can include other objects to construct something complex.
        }
    }

You need to add a navigation link to Status entity inside the User entity. Your Poco objects does not need to be exact match of one entity. They can also include more information from several entities.

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

Without using database view you can achieve only the second solution but you can improve it with non mapped StatusDescription property:

public class User
{
    public int UserId { get;set; }
    public string UserName { get;set; }
    public Status UserStatus { get; set; }

    [NotMapped]
    public string StatusDescription 
    {
        get
        {
            return UserStatus.StatusDescription;
        }

        set
        {
            UserStatus.StatusDescription = value;
        }
    }
}

Upvotes: 1

Related Questions