【发布时间】:2021-06-02 13:27:08
【问题描述】:
我想向我的 API 发送一个包含关系的发布请求,例如:
{
"name": "test",
"description": "test",
"releaseDate": "0001-01-01T00:20:40",
"publisherId": 1
}
其中 publisherId 是外部 id。 我可以让它适用于一对多的关系,但不是多对多。 这是我现在的模型:
public class Game
{
[Required]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime ReleaseDate { get; set; }
public int? PublisherId { get; set; }
public ICollection<int> DeveloperIds { get; set; }
public ICollection<int> CategoryIds { get; set; }
public ICollection<int> PlatformIds { get; set; }
[InverseProperty("PublishedGames")]
[ForeignKey("PublisherId")]
public virtual Company Publisher { get; set; }
[ForeignKey("DeveloperIds")]
public virtual ICollection<GameCompany> Developers { get; set; }
[ForeignKey("CategoryIds")]
public virtual ICollection<GameCategory> Categories { get; set; }
[ForeignKey("PlatformIds")]
public virtual ICollection<GamePlatform> Platforms { get; set; }
}
但我无法将它添加到模型中...
[ForeignKey("DeveloperIds")]
public virtual ICollection<GameCompany> Developers { get; set; }
这个错误是不言自明的,但我不知道这些建议是否正确。
System.InvalidOperationException H结果=0x80131509 Message=无法映射属性“Game.DeveloperIds”,因为它属于“ICollection”类型,不是受支持的原始类型或有效的实体类型。显式映射此属性,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略它。
我也尝试过其他类型,如 IEnumerable、IList、List 和数组,但没有成功。 我该如何解决这个问题?提前致谢
我也不能使用 .NET 5,因为谷歌应用引擎不支持。
编辑: GameCompany 类:
public class GameCompany
{
public int GameId { get; set; }
public Game Game { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
游戏控制器:
[HttpPost]
public ActionResult<GameRepresentation> CreateGame([FromBody] Game newGame)
{
context.Games.Add(newGame);
context.SaveChanges();
var game = context.Games
.Include("Platforms")
.Include("Categories")
.Include("Developers")
.Include("Publisher")
.Single(br => br.Id == newGame.Id);
List<int> PlatformIds = new List<int>();
foreach (GamePlatform platform in game.Platforms)
{
PlatformIds.Add(platform.PlatformId);
}
List<int> CategoryIds = new List<int>();
foreach (GameCategory category in game.Categories)
{
CategoryIds.Add(category.CategoryId);
}
List<int> DeveloperIds = new List<int>();
foreach (GameCompany developer in game.Developers)
{
DeveloperIds.Add(developer.CompanyId);
}
var toReturn = new GameRepresentation
{
Id = game.Id,
Name = game.Name,
Description = game.Description,
ReleaseDate = game.ReleaseDate,
PublisherId = game.Publisher?.Id,
PublisherName = game.Publisher?.Name,
PlatformIds = PlatformIds,
CategoryIds = CategoryIds,
DeveloperIds = DeveloperIds
};
return Created("" ,toReturn);
}
【问题讨论】:
-
你能显示GameCompany类吗?
-
@Serge 添加到原帖
-
你用的是什么版本的网络?
-
使用 .NET Core 3.1
标签: c# .net entity-framework .net-core asp.net-web-api