【问题标题】:How to add a list of objects into an object and store it in database?如何将对象列表添加到对象中并将其存储在数据库中?
【发布时间】:2021-12-13 16:52:17
【问题描述】:

我正在使用 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 的列,我不知道如何解决这个问题。

【问题讨论】:

  • 您缺少尝试存储所示类型对象的代码。
  • “甚至没有创建名为 Apps 的列” - 我不明白为什么会这样。什么会存储在这样的列中?我希望这会为GameModel 对象创建一个表,并且在该表中有一个外键列返回到AccountModel 对象的表中。也许这里的问题只是你有一个错误的期望并且真的没有问题?
  • 您不会将“对象”存储在数据库中;它没有object 数据类型。您使用多个表和主/外键关系。
  • 好吧,对不起,我是新手。所以我应该使用游戏 ID 列表?

标签: c# sql entity-framework ssms


【解决方案1】:

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

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 之间的一对多关系。不要忘记这是您第一次使用模型,并且如果您首先使用代码而不是映射到现有数据库,则需要添加和应用迁移来创建数据库。

详情请见https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多