Hello, I hove following entities:
public class Provider : EntityBase
{
[Column(Order = 120)]
public string Name { get; set; }
public virtual ICollection<Country> Countries { get; set; }
}
public class Country :EntityBase
{
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(10)]
public string Code { get; set; }
}
And following configuration:
public class ProviderConfiguration : EntityTypeConfiguration<Provider>
{
public ProviderConfiguration()
{
HasMany(m => m.Countries)
.WithMany()
.Map(m =>
{
m.MapLeftKey("ProviderId");
m.MapRightKey("CountryId");
m.ToTable("Provider_Countries");
});
}
}
That means a provider can have several countries. The table in sql server look good and as far as I know that is the recommended method to build up many to many relationship. However, when I try to save the children only my provider entity is saved and the children are not saved to the "Provider_Countries" table:
public ProviderService(IRepository<Provider> providerRepository, IRepository<Country> countryRepository)
{
_providerRepository = providerRepository;
_countryRepository = countryRepository;
}
public async Task SaveAsync(Provider provider)
{
var entity = provider;
var countriesToAdd = provider.Countries.ToList();
//Clear existing entities
entity.Countries.Clear();
foreach (var countryToAdd in countriesToAdd)
{
var country = _countryRepository.Get(countryToAdd.Id);
entity.Countries.Add(country);
}
_providerRepository.InsertOrUpdate(entity);
await CurrentUnitOfWork.SaveChangesAsync();
}
Based on the topics I found on the internet that is the recommended approach how to save a many to many relationship. Do you have any idea how I can save the child items?
Nevermind, I fixed it.
My code was
[System.Web.Http.HttpGet]
[DontWrapResult]
public async Task<ActionResult> Get()
{
var countrys = await _countryAppService.GetAllAsync();
return Json(countrys, JsonRequestBehavior.AllowGet);
}
However, because countrys is of type ListResultOutput<CountryViewModel> I need to change it to:
[System.Web.Http.HttpGet]
[DontWrapResult]
public async Task<ActionResult> Get()
{
var countrys = await _countryAppService.GetAllAsync();
return Json(countrys.Items, JsonRequestBehavior.AllowGet);
}
Hi, The attribute does not seem to help very much. I copied my controller from a working version of another project. My method returns: [{"Name":"Germany","Id":2}]
However, the same method with the DontWrapResult returns {"Items":[{"Name":"Germany","Id":2}]}