外键集合为空

时间:2019-05-17 21:48:40

标签: c# ef-code-first entity-framework-core

因此,我尝试使用EF内核获得一些东西。我正在做代码优先,因为这对我来说是最好的(我更喜欢这样做,因为也不必为用户提供数据库)。无论如何,我将要拥有一个包含大量关系的大型数据库,因此我必须使用外键。

但是,即使在数据库中已链接,外键集合始终为null。我有这两种型号:

用户:

[Table("users")]
public class User
{
    [Key]
    [Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("name")]
    [StringLength(15, MinimumLength =2)]
    [Required]
    public string Name { get; set; }

    [Column("password")]
    [StringLength(100)]
    [Required]
    public string Password { get; set; }

    [Column("email")]
    [StringLength(30, MinimumLength =6)]
    [Required]
    public string Email { get; set; }

    public List<UserActivityPoints> Activitypoints { get; set; }
}

UserActivityPoints:

[Table("activitypoints")]
public class UserActivityPoints
{
    [Key]
    [Column("type")]
    public int Type { get; set; }

    [Column("amount")]
    public int Amount { get; set; }

    [Key]
    [Column("user_id")]
    public User User { get; set; }
}

因此,已经很奇怪的一件事是,在数据库中,user_id列变为UserId,但是它已正确链接到用户,如下所示:

A picture of PHPMyAdmin showing it's linked correctly

在我的数据库环境中,我有以下代码:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().ToTable("User");
    modelBuilder.Entity<UserActivityPoints>().ToTable("activitypoints");
}

我运行以下代码:

var i = ProductionDbContext.GetInstance().Users.Find(1).Activitypoints;

下图显示了一条记录:

The record is added in the database

但是,当我调试时,i始终为null,即使用户1在活动点表中有记录。我是在做错事还是在忘记某事?

1 个答案:

答案 0 :(得分:0)

UserActivityPoints中,您在[Key]Type的上方分别有UserId-EFCore认为您正在尝试将两者合并为您的主键。您的UserActivityPoints应该如下所示:

[Table("activitypoints")]
public class UserActivityPoints
{
    [Key]
    [Column("type")]
    public int Type { get; set; }

    [Column("amount")]
    public int Amount { get; set; }

    [Key]
    [Column("user_id")]
    public int UserId { get; set; }

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

我已经删除了密钥,为您提供了一个仅用于ID的列和一个用于User的对象。现在它应该可以正常工作了。 Doc:https://docs.microsoft.com/en-us/ef/core/modeling/keys