I have an issue with a lookup table. I have a form that allows me to select colours from a list that will be part of a team. The update method looks like this:
[HttpPut]
[Route("")]
/// <summary>
/// Update a team
/// </summary>
/// <param name="model">The team model</param>
/// <returns>Nothing</returns>
public async Task<IHttpActionResult> Update(TeamBindingViewModel model)
{
// If our model is invalid, return the errors
if (!ModelState.IsValid)
return BadRequest(ModelState);
// Get our current team
var team = await this.service.GetAsync(model.Id, "Colours");
// Make changes to our team
team.Name = model.Name;
team.Sport = model.Sport;
// Find out which colours need adding and removing
var coloursToRemove = GetDifference(team.Colours, model.Colours);
var coloursToAdd = GetDifference(model.Colours, team.Colours);
// Loop through our colours to remove and remove them
if (coloursToRemove.Count() > 0)
foreach (var colour in coloursToRemove)
team.Colours.Remove(colour);
// Loop through the colours to add and add them
if (coloursToAdd.Count() > 0)
foreach (var colour in coloursToAdd)
team.Colours.Add(colour);
// Update the team
this.service.Update(team);
// Save the database changes
await this.unitOfWork.SaveChangesAsync();
// Return Ok
return Ok(model);
}
private IList<Colour> GetDifference(IList<Colour> firstList, IList<Colour> secondList)
{
// Create a new list
var list = new List<Colour>();
// Loop through the first list
foreach (var first in firstList)
{
// Create a boolean and set to false
var found = false;
// Loop through the second list
foreach (var second in secondList)
{
// If the first item id is the same as the second item id
if (first.Id == second.Id)
{
// Mark it has being found
found = true;
}
}
// After we have looped through the second list, if we haven't found a match
if (!found)
{
// Add the item to our list
list.Add(first);
}
}
// Return our differences
return list;
}
If I put a breakpoint on the unitOfWork.SaveChangesAsync() then I can see that the team colours is using the existing colours already in my database (all the id's match up. But once that SaveChangesAsync executes, it creates a new row in the Colours table with a duplicate of the colour I just selected. I don't want it to create a new row, I want it to use the selected colour.
I am not sure how I can give more information; I hope this is enough of a description for someone to be able to help me!
Update
So I have decided to look at the SQL that is generated. I have a colour in my Colours table that looks like this:
10 Red (Pms200) ff0000
So the Id is 10 , the Name is Red (Pms200) and the Hex is ff0000 . If I select that colour when editing a team and press submit. It runs the Update method shown above and I have changed my DbContext to log the sql by adding this line in the constructor:
this.Database.Log = s => Debug.WriteLine(s);
So, when the SaveChangesAsync code exectues, the following SQL is generated:
Started transaction at 13/04/2015 12:25:03 +01:00
UPDATE [dbo].[Teams]
SET [Name] = @0, [Sport] = @1
WHERE ([Id] = @2)
-- @0: 'Testing' (Type = String, Size = -1)
-- @1: 'ultimate-frisbee' (Type = String, Size = -1)
-- @2: '1' (Type = Int32)
-- Executing asynchronously at 13/04/2015 12:25:03 +01:00
-- Completed in 5 ms with result: 1
INSERT [dbo].[Colours]([Name], [Hex])
VALUES (@0, @1)
SELECT [Id]
FROM [dbo].[Colours]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
-- @0: 'Red (Pms200)' (Type = String, Size = -1)
-- @1: 'ff0000' (Type = String, Size = -1)
-- Executing asynchronously at 13/04/2015 12:25:03 +01:00
-- Completed in 1 ms with result: SqlDataReader
INSERT [dbo].[TeamColours]([TeamId], [ColourId])
VALUES (@0, @1)
-- @0: '1' (Type = Int32)
-- @1: '43' (Type = Int32)
-- Executing asynchronously at 13/04/2015 12:25:03 +01:00
-- Completed in 1 ms with result: 1
Committed transaction at 13/04/2015 12:25:03 +01:00
Closed connection at 13/04/2015 12:25:03 +01:00
Now the problem here is that it should be only inserting something into the TeamColours table and not the Colours table. I can't figure out why....
And because someone has asked to see my UnitOfWork class, here it is:
public class UnitOfWork<TContext> : IUnitOfWork where TContext : DbContext, new()
{
private readonly DbContext context;
private Dictionary<Type, object> repositories;
public DbContext Context { get { return this.context; } }
public UnitOfWork()
{
this.context = new TContext();
repositories = new Dictionary<Type, object>();
}
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
{
if (repositories.Keys.Contains(typeof(TEntity)))
return repositories[typeof(TEntity)] as IRepository<TEntity>;
var repository = new Repository<TEntity>(context);
repositories.Add(typeof(TEntity), repository);
return repository;
}
public async Task SaveChangesAsync()
{
try
{
await this.context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
ex.Entries.First().Reload();
}
}
public void Dispose()
{
this.context.Dispose();
}
}
Although I am certain that is not causing the issue.
try this
public async Task<IHttpActionResult> Update(TeamBindingViewModel model)
{
// If our model is invalid, return the errors
if (!ModelState.IsValid)
return BadRequest(ModelState);
// Get our current team
var team = await this.service.GetAsync(model.Id, "Colours");
// Make changes to our team
team.Name = model.Name;
team.Sport = model.Sport;
//remove
foreach (var colour in team.Colours.ToList())
{
if (!model.Colours.Any(c => c.Id == colour.Id))
team.Colours.Remove(colour);
}
//add
foreach (var colour in model.Colours)
{
if (!team.Colours.Any(c => c.Id == colour.Id))
team.Colours.Add(colour);
}
// Update the team
this.service.Update(team);
// Save the database changes
await this.unitOfWork.SaveChangesAsync();
// Return Ok
return Ok(model);
}
Model.Colors is not associated a context. So your Db Context tries to add new one.
1 -Get colors from repository
var newColours = repository.ListColours(model.Colors.Select(m=>m.Id));
2- Assign new colors to team
team.Colours = newColours;
this.service.Update(team);
await this.unitOfWork.SaveChangesAsync();
EF will automatically operate remove and add operations.
I have not tested this code. But I hope EntityFramework smarter then I thought.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.