C
C#2w ago
Notchu

Need Help With Understanding EF Core and DI in specific case

Hi! Im working on an CRUD WEB API with asp.net how should I pass database context to the subservice? Currently I have a controller that calls service method to get something and return it. FilmController receive request to save film and provides data to DataService& But I need to check if Actors are already in database and if no than I have to create one and save it to db. Here is code for better understanding.
public async Task<ServiceResult<FilmData>> UpdateFilm(FilmDTO filmDto, Guid id)
{
var film = new FilmData(filmDto);

var filmResult = await GetFilmById(id, true);

if (!filmResult.Success)
{
return ServiceResult<FilmData>.Fail(filmResult.ErrorCode, filmResult.Error!);
}

var entity = filmResult.Data!;

entity.Title = film.Title;

entity.ReleaseDate = film.ReleaseDate;

entity.Budget = film.Budget;

entity.Actors.Clear();

var actorTitles = film.Actors.Select(x => x.Name).Distinct().ToList();

var allActors = await _actorResolver.GetOrCreateActorsAsync(actorTitles);

foreach (var actor in allActors.Values)
{
entity.Actors.Add(actor);
}

try
{
await _csvContext.SaveChangesAsync();
}
catch (Exception e)
{
return ServiceResult<FilmData>.Fail(ServiceErrorCodes.SaveFailed, e.Message);
}

return ServiceResult<FilmData>.Ok(entity);

}
public async Task<ServiceResult<FilmData>> UpdateFilm(FilmDTO filmDto, Guid id)
{
var film = new FilmData(filmDto);

var filmResult = await GetFilmById(id, true);

if (!filmResult.Success)
{
return ServiceResult<FilmData>.Fail(filmResult.ErrorCode, filmResult.Error!);
}

var entity = filmResult.Data!;

entity.Title = film.Title;

entity.ReleaseDate = film.ReleaseDate;

entity.Budget = film.Budget;

entity.Actors.Clear();

var actorTitles = film.Actors.Select(x => x.Name).Distinct().ToList();

var allActors = await _actorResolver.GetOrCreateActorsAsync(actorTitles);

foreach (var actor in allActors.Values)
{
entity.Actors.Add(actor);
}

try
{
await _csvContext.SaveChangesAsync();
}
catch (Exception e)
{
return ServiceResult<FilmData>.Fail(ServiceErrorCodes.SaveFailed, e.Message);
}

return ServiceResult<FilmData>.Ok(entity);

}
And here is GetOrCreateActorsClass
public async Task<Dictionary<string, Actor>> GetOrCreateActorsAsync(List<string> actorTitles)
{
List<Actor> actorsFromDatabase = await _csvContext.Actors
.Where(x => actorTitles.Contains(x.Name))
.ToListAsync();

var actorsDict = actorsFromDatabase.ToDictionary(x => x.Name);

var allActors = new Dictionary<string, Actor>();

var actorsToAdd = new List<Actor>();

foreach (var actorDto in actorTitles)
{
if (actorsDict.TryGetValue(actorDto, out var outActor))
{
allActors[actorDto] = outActor;
continue;
}
var actor = new Actor(actorDto);
allActors[actorDto] = actor;
actorsToAdd.Add(actor);
}
_csvContext.Actors.AddRange(actorsToAdd);
return allActors;
}
public async Task<Dictionary<string, Actor>> GetOrCreateActorsAsync(List<string> actorTitles)
{
List<Actor> actorsFromDatabase = await _csvContext.Actors
.Where(x => actorTitles.Contains(x.Name))
.ToListAsync();

var actorsDict = actorsFromDatabase.ToDictionary(x => x.Name);

var allActors = new Dictionary<string, Actor>();

var actorsToAdd = new List<Actor>();

foreach (var actorDto in actorTitles)
{
if (actorsDict.TryGetValue(actorDto, out var outActor))
{
allActors[actorDto] = outActor;
continue;
}
var actor = new Actor(actorDto);
allActors[actorDto] = actor;
actorsToAdd.Add(actor);
}
_csvContext.Actors.AddRange(actorsToAdd);
return allActors;
}
Im currently passing csvContext via DI but as soon as its configured scoped that it will create new context and data wont be saved correctley. What should I do? Or should I just pass dbcontext as param for method?
4 Replies
Notchu
NotchuOP2w ago
Sorry its just complicated to explain Both of this services are Scoped
Kringe
Kringe2w ago
The default scope of a Web API is per HTTPrequest so if youre DI set up is correct it should share the same context
Bobby Bob
Bobby Bob2w ago
Out of curiosity, what is your Web API serving specifically? I'm asking because I'm looking for project ideas to practice C#
Notchu
NotchuOP2w ago
CSV Processing. Upload download data to/from csv and CRUD Operation on it Thank you!

Did you find this page helpful?