【问题标题】:How to build a relationship with Entity Framework如何与实体框架建立关系
【发布时间】:2013-11-09 01:52:06
【问题描述】:

我有两个 SQL 表:

Users ( Id, Username )
Profiles ( Id, UserId, Email )

我有两个班级:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; }
    public Profile profile { get; set; }
}

public class Profile
{
    //[Key]
    //public int Id { get; set; }
    public string Email { get; set; }
}

我有一个选择用户和配置文件作为 JOIN 的视图:

CREATE VIEW [dbo].[Users]
AS SELECT 
    AspNetUsers.UserName, 
    UserProfiles.*
FROM [AspNetUsers]
INNER JOIN UserProfiles ON AspNetUsers.Id = UserProfiles.UserId

我如何(在类中)将用户与配置文件相关联,以便我可以使用 EntityFramework 控制器/视图 crud 构建器?

【问题讨论】:

  • 这不是 EF 的工作方式。您可以(并且应该)直接从数据库表中填充类。你不需要视图。如果您以代码为先,则可以轻松使用您的类模型(当然,没有 cmets)和表格。
  • 视图是一个红鲱鱼。它真的只是无所事事。

标签: c# sql entity-framework relationship


【解决方案1】:

关系和观点是不同的东西。 您可以有实际的视图,或者在结果中组合返回表 X 和表 Y 的查询。 请参阅通过“选择”方法进行投影。

relationships explained

Working with relationships

sample projection query

值得在THE EF SITE 上花费几个小时 如果您对使用 EF 很认真。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多