c# - 如何将对象列表添加到对象中并将其存储在数据库中?
问题描述
我正在使用 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 的列,我不知道如何解决这个问题。
解决方案
我会为这些模型添加一些导航属性。
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.
推荐阅读
- javascript - 在 div JavaScript ajax 中显示输入数据(无 jquery)
- java - OOP 链接类
- c# - 根据位置管理用户池
- python - np.exp 溢出解决方法
- python - GLM R 与 Python
- postman - Newman & Postman:如何使用 Newman 从文件中读取输入
- html - 为什么我在输入电子邮件时没有显示我的订单状态?
- asp.net-mvc-5 - CS0012 类型“XtraReport”在未引用的程序集中定义
- c# - 当玩家移动时需要帮助退出 IEnumerator
- python-3.x - 在数据帧的所有元素中的特定位置插入子字符串(Python)