我有实体框架代码,应该更新名为Asset
的实体。出于某种原因,它没有按预期进行更新。调试以查看此问题的根本原因很困难,因为我没有看到任何例外。
问题出在存储库类中,它始终返回
即使我传入有效的资产无法更新
Book
或Asset
对象,也会发送消息。
模型类
public class Asset
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Book : Asset
{
public string Isbn { get; set; }
public string Edition { get; set; }
public string Publisher { get; set; }
public virtual User User { get; set; }
}
控制器类
[System.Web.Http.Authorize]
public async Task<IHttpActionResult> Put([FromBody] BookViewModel model)
{
string result = null;
try
{
if (model.IsEmpty)
return BadRequest(ModelState);
result = await _assetAssetRepository.Update(Mapper.Map<Book>(model));
return Content(HttpStatusCode.Created, result);
}
catch (Exception ex)
{
return Content(HttpStatusCode.InternalServerError, result);
}
}
存储库类:
public class AssetRepository
{
private readonly GenAppContext _context = new GenAppContext();
public Task<string> Update(Asset asset)
{
try
{
var updateTask = Task<string>.Factory.StartNew(() =>
{
if (!(asset is Book))
return "Please return correct type of asset";
var _asset = _context.Assets.SingleOrDefault(x => x.Id == asset.Id);
if (_asset == null)
throw new ArgumentNullException(nameof(_asset));
_asset.Name = asset.Name;
((Book) _asset).Edition = ((Book) asset).Edition;
((Book) _asset).Publisher = ((Book) asset).Publisher;
((Book) _asset).Isbn = ((Book) asset).Isbn;
_context.Assets.AddOrUpdate(_asset);
return _context.SaveChanges() > 0
? "Asset has been updated successfully"
: "Asset could not be updated";
});
return updateTask;
}
catch (Exception ex)
{
return Task<string>.Factory.StartNew(() => ex.Message + " " + ex.StackTrace);
}
}
}