0

I working on a Blazor web application server side written in C#. I have an issue that I can't get values of properties employee id and department code from object parameter to insert value on table.

I get compile-time error when try to get value for property employee ID - like this:

Error CS1061: 'object' does not contain a definition for 'employeeID' and no accessible extension method 'employeeID' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

When I check owner object after break point hit and data passed as below :

ValueKind = Object : "{"employeeID":1222,"employeeName":0,"departementCode":"211","jobCode":"1221","ownerType":null,"departementName":"ahmed"}"

[HttpPost]
public ActionResult AddOwnerFile(object owner)
{
    string ownerfileno = owner.employeeID;
    string departementCode = owner.departementCode;

    var sql = "INSERT INTO Owner (OwnerFileNo, DepartementCode) VALUES ({0}, {1})";

    var rowsAffected = _context.Database.ExecuteSqlRaw(sql, ownerfileno, departementCode);

    return Ok();
}

I expected the result would be:

ownerfileno=1222
departementCode=211

Last updated post

var employeeID = owner.GetType()
                      .GetProperties()
                      .First(o => o.Name == "employeeID")
                      .GetValue(owner, null);

I try to get the value of employeeID, but I get an error at runtime:

System.InvalidOperationException: 'Sequence contains no matching element'

How to solve this error, please?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ahmed abdelaziz
  • 427
  • 1
  • 8

1 Answers1

1

Instead of using object type, create the model class for the request body.

public class Owner
{
    public int EmployeeID { get; set; }
    public int EmployeeName { get; set; }
    public string DepartementCode { get; set; }
    public string JobCode { get; set; }
    public int? OwnerType { get; set; }
    public string DepartementName { get; set; }
}

Amend the AddOwnerFile method to receive a parameter with the Owner type.

While it always recommends using the parameterized query to avoid SQL injection. Reference: Passing the parameter for SQL Queries in EF Core

[HttpPost]
public ActionResult AddOwnerFile([FromBody]Owner owner)
{
    var ownerfileno = new SqlParameter("@employeeID", owner.employeeID);
    var departementCode = new SqlParameter("@departementCode", owner.departementCode);

    var sql = "INSERT INTO Owner (OwnerFileNo, DepartementCode) VALUES (@employeeID, @departementCode)";
    var rowsAffected = _context.Database.ExecuteSqlRaw(sql, ownerfileno, departementCode);

           
    return Ok();
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46