Web Api POST inserted Data without Id created - asp.net-web-api

I am learning to pass data to Web API. I created A web Api Project and I am using Ado.Net Entities DataModel base On DataBase First Approach for this project and I encountered a problem as described below.
I created a Controller.
Here I use [FromBody] to receive the JSON data:
public class CustomerController : ApiController
{
   ICustomerRepository repository = new CustomerRepository()
    [HttpPost]
    public void PostContact([FromBody] Customer contact)
    {
        repository.Add(contact);
    }
 
...
}
I'm using the repository pattern to handle CRUD.
Here are my classes:
public interface ICustomerRepository
{
IEnumerable<Customer> GetAll();
Customer GetById(int CustId);
int Update(Customer Cust);
void Add(Customer Cust);
void Delete(int CustId);
}
public class CustomerRepository : ICustomerRepository
{
// using Ado.net Entities
MyEntities ctx = new MyEntities();
public void Add(Customer contact)
{      
var addedContact = ctx.Customers.Add(contact);
ctx.SaveChanges();
}
...
}
This is the table in SQL Server:
CustId              int
CustomerName        nvarchar(50)
CustomerPassword    nvarchar(50)
CustomerEmailAddr   nvarchar(100)
CustomerMobileNo    nvarchar(20)
CreatedOn           DateTime   (only this allows Nulls)
My Web API is ok when I do a GetById for the first record manually inserted into the table thru SSMS. I used Fiddler to do testing for a 2nd customer.
I used POST selection in Fiddler
I added
Accept: application/json
Content-Type : application/json
I added this JSON data string in the request-body section for post
{
"CustomerName": "David2",
"CustomerPassword": "12345672",
"CustomerEmailAddr": "123,Motoway ",
"CustomerMobileNo": "968772322",
"CreatedOn": "04/25/2017"
}
Problem when doing a POST in Fiddler:
There is no CustID generated. There is a new row with CustID 0
The table only shows the rest of the data without CustId (CustId 0)
Update
I have set PrimaryKey for CustId, and set up these in properties:
Is Identity: yes,
Identity Increment: 1
Identity Seed: 1
When I execute the POST I get this error message:
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Customers' when IDENTITY_INSERT is set to OFF
Update:
This is the class name inside the Edmx:
using System;
using System.Collections.Generic;
public partial class Customer
{
public int CustId { get; set; }
public string CustomerName { get; set; }
public string CustomerPassword { get; set; }
public string CustomerEmailAddr { get; set; }
public string CustomerMobileNo { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
}

Is CustId is primary key and auto increment? if not then make CustId primary key with auto increment

Related

SQlite Update Statement in xamarin forms

I have an SQlite table with 4 Columns in Xamarin app.
I've already inserted 3 columns and now i need an update statement to Update 4th column with some values using for loop.
(OR)
Please suggest any better/other method to do the same.
Do you want to update the record in the sqlite DB?
If so you can use this model to update the record in the DB.prijem.BCode is PrimaryKey, we set the type of PrimaryKey is int and AutoIncrement, So, if the model's PrimaryKey is not equal zero, this record stored in the DB, we can update this record by the Model.
readonly SQLiteAsyncConnection _database;
public PrijemDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Prijem>().Wait();
}
public Task<int> SavePrijemAsync(Prijem prijem)
{
if (prijem.BCode != 0)
{
return _database.UpdateAsync(prijem);
}
else
{
return _database.InsertAsync(prijem);
}
}
Here is my model.
public class Prijem
{
[PrimaryKey, AutoIncrement, Unique]
public int BCode { get; set; }
public string Name { get; set; }
public string FirmName { get; set; }
public string ItemCode { get; set; }
public string Count { get; set; }
}
Here is link about how to execute CRUD, you can refer to it.
https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
Here is a demo about it.
https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/getstarted-notes-database/

Entity Framework controller returning too much data

I created an Entity Framework app using NetCore 2.2. It's just a simple app that has models and controllers that were scaffolded from my database.
In my database, if I run this query, I will get the expected 4 rows of data back.
select * from BookSeries where mainBookID = 'akfj36hf'
In my controller, I'm trying to mimic the SQL above, with this code:
[HttpGet("BookSeriesByMain/{id}")]
public async Task<List<BookSeries>> GetBookSeries(string id)
{
return await _context.BookSeries.Where(n => n.MainBookId == id).ToListAsync();
}
When I hit the controller URL, with the same id of 'akfj36hf', it is returning EVERY row in the database for that table(BookSeries). Not just the expected 4 rows.
Here is my model:
public partial class BookSeries
{
public string BookLinkId { get; set; }
public string MainBookId { get; set; }
public string ChildBookId { get; set; }
public int? OrderId { get; set; }
public virtual BookList MainBook { get; set; }
}
I'm kind of at a loss as to what I did wrong.
Does anyone see anything that I messed up?
THanks!

OData-query is throwing error for $expand query

There are two tables "Task" and "Client". Both this tables are related with ClientId (foreign key).
In this query I'm trying to get the client name based on ClientId from Task table with $expand keyword. Below is the query and Entity classes.
OData Query : http://localhost:52484/Task?$expand=Client($select=Name)
public class Task: GeneralTask
{
public Task() { }
public Task(
int clientId,
string title,
)
{
this.Title = title;
this.ClientId = clientId;
}
}
public abstract class GeneralTask
{
protected GeneralTask()
{
}
public string Title { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
}
But I get the below error.
Error Message :"The query specified in the URI is not valid. The property 'Client' cannot be used in the $expand query option."
Any help would be appreciated.
We need to enable OData Model Bound Attributes which you can do globally with the middle line in the following block(WebApiConfig.cs file)
ODataModelBuilder builder = new ODataConventionModelBuilder();
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); //new line
builder.EntitySet<DB.Project>("Projects");

Web API parameter binding not working

I have two entity classes Donor and User. Donor is subclass of User as given below
public abstract class User {
[Key]
public long Id { get; set; }
...
}
public class Donor : User {
public string AlternateMobileNumber { get; set; }
...
}
A web api controller action shown below receives POST request with JSON data in the body
public class DonorsController : ApiController {
//POST: api/Donors/EditDonor
[HttpPost]
public HttpResponseMessage EditDonor([FromBody] Donor donor) {
...
}
}
Here is how the post request looks like
POST http://localhost:xxxxx/Donor/api/Donors/EditDonor HTTP/1.1
Content-Length: 477
Cache-Control: no-cache
Content-Type: application/json;charset=UTF-8
Accept: */*
...
{"Id":12,"UserId":"donor9#abc.com","FirstName":"firstname9c","MiddleName":"M","LastName":"lastname9","Gender":"Male","MobileNumber":"7777777777","BloodGroup":"A+ve","OfficeLocality":{"Id":2,"Name":"Malad"},"ResidenceLocality":{"Id":2,"Name":"Malad"},"Organization":"organization9","Designation":"designation9","TimesDonated":1,"DateLastDonated":"Mon Dec 01 00:00:00 GMT+05:30 2014","LastDonatedAt":"Hosp 1","IsSDPDonor":false,"IsIntrestedDonor":false,"Comments":"Some Comment"}
The issue is that the Donor object is empty (not null but empty, without values applied to properties of Donor).
If I change Donor object and use a Data Transfer Object (DonorDO) with the same properties but without any inheritance, then the properties are correctly populated in that Data object. For example the Donor Data Object is like below.
//Plain Data Transfer Object without inheritance
public class DonorDO {
public long Id { get; set; }
public string AlternateMobileNumber { get; set; }
...
}
Why does DonorDO get its property values bound correctly, while the Donor Entity object remains empty with none of the properties bound. Is it related to inheritance or some other issue.
I've noticed that you are POSTing to "http: // localhost : xxxxx/Donor/api/Donors/EditDonor" which is wrong, you need to POST to "http: // localhost : xxxxx/api/Donors" (you need to POST to the controller base address only, and controller name should be after "api" not before).
This code is 100% working :
using System.Net;
using System.Net.Http;
using System.Web.Http;
//[Authorize]
public class DonorsController : ApiController
{
[HttpGet]
public Donor Get(int id)
{
return new Donor
{
Id = id,
AlternateMobileNumber = "0000",
};
}
//POST: api/Donors/EditDonor
[HttpPost]
public HttpResponseMessage EditDonor([FromBody] Donor donor)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
public abstract class User
{
public long Id { get; set; }
}
public class Donor : User
{
public string AlternateMobileNumber { get; set; }
}
Now, using fiddler I called this method as you can see in the bellow image, and on the controller side you can see the passed donor argument.
Hope this helps.

Get The Table Name Of Model In T4 Template

I am using MVC4 ,T4 Scaffolding and EF5.
I Created a model,
namespace wbtest.Models
{
[Table(name: "Pay_Employees_Mst", Schema = "Test")]
public class Employee
{
public int EMPLOYEE_ID { get; set; }
public string EMPLOYEE_CODE { get; set; }
}
}
I need to get the annotation of table name "Pay_Employees_Mst" for db context .Currently getting ModelName Employee.
Please Help.
I got it through,
String entityName1 = (context as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext
.CreateObjectSet<Employee>()
.EntitySet.Name;

Resources