Ef Core 插入具有关系的实体

Ef Core insert entity with relationship

我在 ef core 3.1 和 sql 服务器插入具有关系的实体时遇到问题。

我要插入的实体是有国家关系的玩家

public class Player{
        [Key]
        public Guid Id {get;set;}
        [ForeignKey("Country")]
        public int CountryId { get; set; }
        public Country Country { get; set; } 
        ...
}
public class Country{
        [key]
        public int Id {get;set;}
        public string Name {get;set;}
        ...
}

我想通过将 CountryId 设置为现有国家/地区 ID 来插入它,并且我希望能够通过添加完整的国家/地区实体而不是 ID(让它同时插入)来插入它

是否可以在不加载完整的国家/地区实体并设置 Player.Country = 国家/地区的情况下执行此操作,或者这是获得关系所必需的东西?

目前的完成方式我得到一些 json 与玩家和 countryId 然后使用我的数据库上下文做一个简单的 _context.Player.Add(player) 然后 _context.SaveCahnges() .

by adding the full country entity and not the id (having it insert both)

我想你是误会了:在数据库中,只有CountryIdCountry 实体并未直接保存在 Player table 中,而只是使用其 ID 对国家/地区的引用。

所以你有两个选项来设置播放器上的国家。通过直接分配国家 ID:

player.CountryId = someCountryId;

或者从您的数据库中分配国家实体:

player.Country = existingCountry;

为了使后一个工作正常,EntityFramework 需要 跟踪 国家/地区实体。这通常意味着您必须从数据库中加载它。

如果您想提供 API 来创建播放器,那么只传递国家 ID 通常是更灵活的方法。