具有关系的EF核心插入实体

时间:2020-05-17 22:13:27

标签: .net-core asp.net-core-webapi ef-core-3.0

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

我要插入的实体是与国家/地区有关系的玩家

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 = country的情况下执行此操作,或者是获得关系所需的某些东西?

目前,我使用播放器和countryId获取一些json,然后使用我的数据库上下文执行一个简单的_context.Player.Add(player),然后是_context.SaveCahnges()。

1 个答案:

答案 0 :(得分:0)

通过添加完整的国家/地区实体而不是ID(必须同时插入两者)

我认为您对此有误解:在数据库中,只有CountryIdCountry实体不会直接保存在Player表中,而只是使用其ID引用到该国家。

因此,您有两个选项可以在播放器上设置国家/地区。通过直接分配国家/地区ID:

player.CountryId = someCountryId;

或通过从数据库中分配国家/地区实体:

player.Country = existingCountry;

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

如果您想提供一个用于创建玩家的API,那么通常只需传递国家/地区ID是更灵活的方法。