Entity Framework Core with ASP.NET Core Web API and SQL Server (+ Xamarin.Forms)

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

Question

I have a Xamarin.Forms project with a user registration page, which sends a serialized Customer object via HttpClient to an ASP.NET Core Web API Controller's [HttpPost] method. The body of this [HttpPost] method is supposed to add a row to a Customers table in an SQL Server database hosted in Azure, via Entity Framework Core.

This is the RegistrationController class in my ASP.NET Core Web API project:

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

And this is the RegistrationContext class:

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

The Azure SQL Server database is configured in the Startup.cs file:

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

For some reason, I keep getting an HTTP 500 status code as a response when performing the HttpClient PostAsync method from the Xamarin.Forms client application, which most likely means there is something wrong with the code inside the body of the RegistrationController (or RegistrationContext) in the Web API.

Testing on localhost reveals this exception at await _context.SaveChangesAsync();:

{System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Id', table 'zwabydb.dbo.Customers'; column does not allow nulls. INSERT fails. The statement has been terminated.

Does Entity Framework Core not assign the Id integer property of the Customer object automatically? (I set it as the primary key in the SQL Server database). If I assign a value to the Id property manually in the [HttpPost] method, say 1, now I get a 200 OK.

Thank you!

1
1
11/1/2017 3:20:09 AM

Accepted Answer

This depends on how you setup your SQL database. If you have an int Id column, you need to set the seed, and autoincrement properties, to have it automatically define a value in that column.

If your Id is a string, then you will need to manually define a value. Normally something like a GUID. e.g. Guid.NewGuid().ToString()

0
11/1/2017 3:50:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow