DOD*_*ODO 6 c# entity-framework-core asp.net-core
我创建了一个 Web API。我使用过 Net Core 6 和 Entity 框架。在这个方法中我想保存两个实体。StockPosition 已保存,但 StockTransaction 存在一些问题。我有一个错误:
System.NotSupportedException:不支持“System.IntPtr”实例的序列化和反序列化。路径:$.TargetSite.MethodHandle.Value。---> System.NotSupportedException:不支持“System.IntPtr”实例的序列化和反序列化。
数据dto:
public class StockPositionBuyDto
{
public int Id { get; set; }
public int IdCurrency { get; set; }
public decimal Count { get; set; }
public decimal Price {get; set; }
public decimal Fee { get; set; }
}
public class StockTransaction
{
public int Id { get; set; }
public StockPosition Position { get; set; }
public string Type { get; set; }
public decimal Count { get; set; }
public decimal Price { get; set; }
public decimal Fee { get; set; }
public Currency Currency { get; set; }
}
public IActionResult newStockPosition(StockPositionBuyDto dto)
{
try
{
string jwt = Request.Cookies["jwt"];
var token = jwtService.verify(jwt);
int userId = int.Parse(token.Issuer);
User user = userRepository.findById(userId);
Currency currency = this.currencyRepository.getById(dto.IdCurrency);
StockPosition stockPosition = new StockPosition
{
Stock = this.stockRepository.getById(dto.Id),
Count = dto.Count,
User = user
};
StockPosition position = this.stockPositionRepository.create(stockPosition);
StockTransaction transaction = new StockTransaction
{
Type = "buy",
Count = dto.Count,
Price = dto.Price,
Fee = dto.Fee,
Currency = currency,
Position = position
};
StockTransaction transactionSaved = this.stockTransactionRepository.create(transaction);
return Ok("Ok");
}
catch (Exception ex)
{
return Unauthorized(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
用于保存的存储库。
public StockTransaction create(StockTransaction transaction)
{
context.stockTransactions.Add(transaction);
transaction.Id = context.SaveChanges();
return transaction;
}
Run Code Online (Sandbox Code Playgroud)
问题在于:
...
catch(Exception ex) {
return Unauthorized(ex)
}
Run Code Online (Sandbox Code Playgroud)
方法Unauthorized本身尝试序列化ex但不能,抛出您看到的错误。在这种情况下,错误消息System.NotSupportedException: Serialization and deserialization of 'System.IntPtr'.... 肯定会令人困惑。尝试返回
...
catch {
return new JsonResult(new {error=ex.Message});
}
Run Code Online (Sandbox Code Playgroud)
会得到正确的错误。感谢@Andrew Williamson 指出了正确的方向。
| 归档时间: |
|
| 查看次数: |
6499 次 |
| 最近记录: |