首页 > 解决方案 > 如何将对象列表添加到对象中并将其存储在数据库中?

问题描述

我正在使用 MVC C# 我有一个模型:

    public class AccountModel
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public List<GameModel> Apps { get; set; }
    public bool IsUseless { get; set; }
}

和一个游戏模型:

    public class GameModel
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public bool VacBanned { get; set; }
}

我正在尝试使用具有 N 个游戏的实体帐户存储在帐户数据库中。但是实体框架甚至没有创建一个名为 Apps 的列,我不知道如何解决这个问题。

标签: c#sqlentity-frameworkssms

解决方案


我会为这些模型添加一些导航属性。

public class AccountModel
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public ICollection<GameModel> Apps { get; set; }
    public bool IsUseless { get; set; }
}

public class GameModel
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public bool VacBanned { get; set; }
    [ForeignKey(nameof(Account))]
    public int AccountId { get; set; }
    public AccountModel Account { get; set; }
}

如果您正确设置了 DBContext(您没有在此处提供),上述内容应该会自动映射 AccountModel 和 GameModel 之间的一对多关系。不要忘记这是您第一次使用模型,并且如果您首先使用代码而不是映射到现有数据库,您将需要添加和应用迁移来创建数据库。

See https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli for details.


推荐阅读