ASP.NET WebAPI不会将记录插入数据库

时间:2013-11-05 12:45:38

标签: c# asp.net asp.net-web-api

我在数据库中插入记录时遇到了困难。实际上我不知道出了什么问题。

我想做什么:我想向Web API插入一个带有POST请求的新Club实体。

会发生什么:即使我调用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而不是俱乐部变量,也会返回成功代码。

俱乐部存储库代码:

 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();           
    }

1 个答案:

答案 0 :(得分:0)

实际上问题在于序列化。我制作了实体的DTO对象,一切都很顺利。