C# 在这种情况下,如何在不定义数据库外键的情况下使查找字段工作?

C# 在这种情况下,如何在不定义数据库外键的情况下使查找字段工作?,c#,sql,entity-framework,.net-core,C#,Sql,Entity Framework,.net Core,代码如下(数据库优先): C#代码: UserTypeId已映射,UserType未映射。有什么想法让它起作用? < P>如果我们认为这是一对多的关系。然后使用dataanotation进行映射将是这样的 public partial class User { [Key] public System.Guid Id { get; set; } public string Name { get; set; } public string Description {

代码如下(数据库优先):

C#代码:


UserTypeId
已映射,
UserType
未映射。有什么想法让它起作用?

< P>如果我们认为这是一对多的关系。然后使用dataanotation进行映射将是这样的

public partial class User
{
    [Key]
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int UserTypeId { get; set; }
    public UserType UserType { get; set; }
}

public partial class UserType
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    [ForeignKey("UserTypeId")]
    public System.Collections.Generic.ICollection<User> Users { get; set; }
}

我已经测试过了。但是我把表名映射放在上下文模型中,我现在看到了,我的不好。我想知道是否有任何方法可以让它在不调用Include()的情况下工作?老实说,在第一次使用ef时,我也这么认为。到目前为止,include是一种方法。如果不显式指定每个实体,就无法让它加载所有相关实体?您可以使用延迟加载,但它将运行另一个查询来加载用户类型。
[Table("Users")]
public class User
{
    [Key]
    public Guid Id { get; set; }

    public string Name { get; set; }

    [ForeignKey(nameof(UserType))]
    public int UserTypeId { get; set; }

    public UserType UserType { get; set; }
}

[Table("UserTypes")]
public class UserType
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }
}
public partial class User
{
    [Key]
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int UserTypeId { get; set; }
    public UserType UserType { get; set; }
}

public partial class UserType
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    [ForeignKey("UserTypeId")]
    public System.Collections.Generic.ICollection<User> Users { get; set; }
}
var data = await _dbcontext.Users.Include(x => x.UserType).ToListAsync();