【问题标题】:Entity Framework Core with ASP.NET Core Web API and SQL Server (+ Xamarin.Forms)带有 ASP.NET Core Web API 和 SQL Server 的 Entity Framework Core (+ Xamarin.Forms)
【发布时间】:2018-04-12 20:48:12
【问题描述】:

我有一个带有用户注册页面的 Xamarin.Forms 项目,它通过 HttpClient 将序列化的 Customer 对象发送到 ASP.NET Core Web API 控制器的 [HttpPost] 方法。这个 [HttpPost] 方法的主体应该通过 Entity Framework Core 向 Azure 中托管的 SQL Server 数据库中的客户表添加一行。

这是我的 ASP.NET Core Web API 项目中的 RegistrationController 类:

[Route("api/[controller]")]
public class RegistrationController : Controller
{
    private readonly RegistrationContext _context;

    public RegistrationController(RegistrationContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] Customer customer)
    {
        var customerEntry = new Customer
        {
            FirstName = customer.FirstName,
            LastName = customer.LastName,
            EmailAddress = customer.EmailAddress,
            PhoneNumber = customer.PhoneNumber
        };

        try
        {
            _context.Add(customerEntry);
            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }

        return Ok(true);
    }
}

这是 RegistrationContext 类:

public class RegistrationContext : DbContext
{
    public virtual DbSet<Customer> Customers { get; set; }

    public RegistrationContext(DbContextOptions<RegistrationContext> options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>(entity =>
        {
            entity.Property(e => e.FirstName).IsRequired();
            entity.Property(e => e.LastName).IsRequired();
            entity.Property(e => e.EmailAddress).IsRequired();
            entity.Property(e => e.PhoneNumber).IsRequired();
        });
    }
}

Azure SQL Server 数据库在 Startup.cs 文件中配置:

public void ConfigureServices(IServiceCollection services)
    {
        container.services.AddMvc();

        var connection = @"Server=myAzureSQLServerUrl;Database=myDatabaseName;User Id=mySQLServerLoginId;Password=mySQLServerPassword;";

        services.AddDbContext<RegistrationContext>(options => options.UseSqlServer(connection));
    }

由于某种原因,在从 Xamarin.Forms 客户端应用程序执行 HttpClient PostAsync 方法时,我不断收到 HTTP 500 状态代码作为响应,这很可能意味着 RegistrationController 主体内的代码有问题(或 RegistrationContext)在 Web API 中。

在 localhost 上的测试在 await _context.SaveChangesAsync(); 处发现了这个异常:

{System.Data.SqlClient.SqlException (0x80131904):无法将值 NULL 插入到列“Id”、表“zwabydb.dbo.Customers”中;列不允许空值。插入失败。声明已终止。

Entity Framework Core 不会自动分配 Customer 对象的 Id 整数属性吗? (我将它设置为 SQL Server 数据库中的主键)。如果我在 [HttpPost] 方法中手动为 Id 属性赋值,比如 1,现在我得到 200 OK。

谢谢!

【问题讨论】:

  • 如果你有 500,你应该在你的日志文件中查看更多细节,或者在你的服务中设置一个断点并调试它
  • 除了数据库,服务也托管在Azure中
  • 尝试在本地加载这个项目,并使用 Postman 连接到它。然后它应该抛出一个错误并中断,向您显示实际原因。
  • {System.Data.SqlClient.SqlException (0x80131904):无法将值 NULL 插入到列 'Id'、表 'zwabydb.dbo.Customers' 中;列不允许空值。插入失败。该语句已终止。我以为 Entity Framework Core 会自动分配 Customer 对象的 Id 属性,因为它是 int 主键?

标签: sql-server azure asp.net-core xamarin.forms entity-framework-core


【解决方案1】:

这取决于您如何设置 SQL 数据库。如果您有一个 int Id 列,则需要设置种子和自动增量属性,以使其自动在该列中定义一个值。

如果您的 Id 是一个字符串,那么您将需要手动定义一个值。通常类似于 GUID。例如Guid.NewGuid().ToString()

【讨论】:

  • 太棒了,它现在完美运行。非常感谢亚当!
猜你喜欢
  • 2019-05-15
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2020-08-09
  • 2020-09-06
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
相关资源
最近更新 更多