我在数据库中插入记录时遇到了困难。我不知道实际上出了什么问题。
我想要做的:我想插入一个新的俱乐部实体,它带有一个对 Web API 的 POST 请求。
会发生什么:即使我调用 UnitOfWork 对象的 Save() 方法,该方法在上下文中调用 SaveChanges(),也没有插入任何内容。
请求的代码如下:
public async Task<bool> Create(Club club)
{
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(club));
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await Client.PostAsync("api/clubs/Add", httpContent); // client is of type HttpClient
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception e)
{
... error handling here ...
}
return true;
}
从 API 插入记录的代码:
[HttpPost]
public HttpResponseMessage Add(Club club)
{
UnitOfWork.ClubsRepository.Add(club);
UnitOfWork.Save();
var response = Request.CreateResponse<Club>(HttpStatusCode.Created, club);
return response;
}
UnitOfWork 类:
public class UnitOfWork : IDisposable
{
private FootballTransfersContext context = new FootballTransfersContext();
private IClubsRepository clubsRepository;
private IPlayersRepository playersRepository;
private ITransfersRepository transfersRepository;
private ICountriesRepository countriesRepository;
private IPositionsRepository positionsRepository;
private bool disposed;
public IClubsRepository ClubsRepository
{
get
{
if (this.clubsRepository == null)
this.clubsRepository = new ClubsRepository(context);
return this.clubsRepository;
}
}
public IPlayersRepository PlayersRepository
{
get
{
if (this.playersRepository == null)
this.playersRepository = new PlayersRepository(context);
return this.playersRepository;
}
}
public ITransfersRepository TransfersRepository
{
get
{
if (this.transfersRepository == null)
this.transfersRepository = new TransfersRepository(context);
return this.transfersRepository;
}
}
public ICountriesRepository CountriesRepository
{
get
{
if (this.countriesRepository == null)
this.countriesRepository = new CountriesRepository(context);
return this.countriesRepository;
}
}
public IPositionsRepository PositionsRepository
{
get
{
if (this.positionsRepository == null)
this.positionsRepository = new PositionsRepository(context);
return this.positionsRepository;
}
}
public void Save()
{
context.SaveChanges();
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
UnitOfWork 对象包含所有存储库并使用您可能建议的单个数据库上下文。有趣的是,即使我尝试插入 null 而不是 club variable ,它也会返回成功代码。
俱乐部存储库代码:
public class ClubsRepository : IClubsRepository
{
private FootballTransfersContext db;
public ClubsRepository()
{
this.db = new FootballTransfersContext();
}
public ClubsRepository(FootballTransfersContext context)
{
this.db = context;
}
public IQueryable<Club> GetAll()
{
return db.Clubs;
}
public Club GetById(int id)
{
Club club = db.Clubs.FirstOrDefault(c => c.ClubID == id);
return club;
}
public void Add(Club club)
{
db.Clubs.Add(club);
}
public void Update(Club club)
{
db.Entry(club).State = EntityState.Modified;
}
public void Delete(int id)
{
Club club = GetById(id);
db.Clubs.Remove(club);
}
public IEnumerable<Club> GetClubsBySearchTerm(string search)
{
var results = db.Clubs.Where(x => x.ClubName.IndexOf(search) != -1);
return results;
}
public IEnumerable<Club> GetClubsBySearchTermMatchBeginning(string search)
{
var results = db.Clubs.Where(x => x.ClubName.StartsWith(search));
return results;
}
public Club GetClubByName(string name)
{
Club clubFound = db.Clubs.FirstOrDefault(x => x.ClubName == name);
return clubFound;
}
public bool IsUniqueClub(string oldName, string oldManager, Club club, ref bool uniqueClubName, ref bool uniqueManager)
{
if (club.ClubName != oldName)
{
if (db.Clubs.FirstOrDefault(x => x.ClubName == club.ClubName) != null)
{
uniqueClubName = false;
return false;
}
}
if (club.Manager != oldManager)
{
if (db.Clubs.FirstOrDefault(x => x.Manager == club.Manager) != null)
{
uniqueManager = false;
return false;
}
}
return true;
}
}
这是来自客户端应用程序控制器的操作:
[Authorize(Roles = "Admin")]
[HttpPost]
public async Task<ActionResult> Create(Club club)
{
if (ModelState.IsValid)
{
Club clubFound = await (clubsRequestClient as ClubsRequestClient).RequestClubByName(club.ClubName); //UnitOfWork.ClubsRepository.GetClubByName(club.ClubName);
if (clubFound != null)
{
ViewBag.CountryID = new SelectList(await countriesRequestClient.GetAll(), "CountryID", "CountryName");
ModelState.AddModelError("", "The club already exists in the database!");
return View(club);
}
else
{
bool isSuccess = await (clubsRequestClient as ClubsRequestClient).Create(club);
//UnitOfWork.ClubsRepository.Add(club);
if (isSuccess)
{
//UnitOfWork.Save();
TempData["SuccessMessage"] = "Club successfully added.";
return RedirectToAction("Index", "Home");
}
}
}
return View();
}