Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 在EF codefirst中映射FK关系_Entity Framework_Entity_Ef Code First_Code First - Fatal编程技术网

Entity framework 在EF codefirst中映射FK关系

Entity framework 在EF codefirst中映射FK关系,entity-framework,entity,ef-code-first,code-first,Entity Framework,Entity,Ef Code First,Code First,假设我有两张表,如: Table:User ------------- - UserId [pk] - UserName - StatusId [fk] Table: Status ------------- - StatusId [pk] - StatusDescription 现在让我们假设我想在我的poco中显示StatusDescription,如: public class User { int UserId{get;set;} string UserName{get;set;}

假设我有两张表,如:

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

Table: Status
-------------
- StatusId [pk]
- StatusDescription
现在让我们假设我想在我的poco中显示StatusDescription,如:

public class User
{
int UserId{get;set;}
string UserName{get;set;}
int StatusId{get;set;}
string StatusDescription{get;set;}
}
是否可以在EF中映射此项?或者,我只能通过以下方式实现这一点:

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

有什么想法吗?提前感谢。

如果不使用数据库视图,您只能实现第二个解决方案,但您可以使用非映射的
状态描述
属性对其进行改进:

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;
        }
    }
}

您可以创建一个扩展方法来生成具有任何复杂属性的POCO对象

  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.
        }
    }

您需要在用户实体内添加指向状态实体的导航链接。您的Poco对象不需要与一个实体完全匹配。它们还可以包含来自多个实体的更多信息。

感谢您的回答,这是我正在考虑的,但使用AutoMapper之类的工具。。。