Unable to access data annotation from partial class - asp.net

Using ASP.NET MVC pattern I have an Entity Framework stored in the Models->Northwind which includes Region.cs class. I also have a Partial Folder which contains RegionalPartial.cs which includes Data annotation for region.cs
Here is the Directory structure
The Region.cs looks like :
namespace Map.Models.Northwind
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Region
{
public int RegionID { get; set; }
public string RegionDescription { get; set; }
}
}
and the RegionPartial.cs is like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Map.Models.Northwind.Partials
{
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(RegionMetaData))]
public partial class Region {}
public class RegionMetaData
{
[Required]
[Display(Name = "REGION DESCRIPTION")]
public object RegionDescription { get; set; }
}
}
but the Region.cs is not using the data annotation stored in the RegionPartial.cs! Why is this happening and how I can fix this?

Change the namespace in RegionPartial.cs from
Map.Models.Northwind.Partials
to
Map.Models.Northwind

Related

.NET 5 WEB API not returning response in postman and browser

.NET 5 WEB API not returning response in postman and browser. Please help me to resolve this issue.
Here is the code:
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RestSharp;
namespace WebAPIApplication.Controllers
{
[Route("api")]
[ApiController]
[Produces(MediaTypeNames.Application.Json)]
[Consumes(MediaTypeNames.Application.Json)]
public class ApiController : ControllerBase
{
[HttpGet("public")]
public IActionResult myPublic()
{
MyStatus _status = new MyStatus();
return Ok(_status);
}
}
}
Here is the response:
{}
return Ok(_status);
Here is the response: {}
Please check and make sure you defined properties well in your class MyStatus, perhaps you defined them as fields not properties, which cause this issue.
public class MyStatus
{
public int StatusCode;
//...
To fix the issue, can modify it as below
public class MyStatus
{
public int StatusCode { get; set; }
//...

Handle Oracle Database Connection in Dapper

I am trying to connect to the Oracle Database and trying to execute a query.
So below is my Model Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace TestAPI.Models
{
public class TestAPIModel
{
[Key]
public int PRIO_CATEGORY_ID { get; set; }
public int LANG_ID { get; set; }
public System.DateTime REC_DATE { get; set; }
public int REC_USER { get; set; }
public Nullable<int> RFCH_ID { get; set; }
public string DESCR { get; set; }
public string COL_DESCR { get; set; }
public string ROW_DESCR { get; set; }
public string ABBR { get; set; }
}
}
DBContext Class is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace TestAPI.Models
{
public class TestAPIContext: DbContext
{
public DbSet<TestAPIModel> details { get; set; }
}
}
Now trying to create the Controller with the Dapper, now the issue is in most of the forums it is trying to connect to SQL Database. I am trying to access Oracle DB and return the result in JSON format .So if I give
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Web.Http.Description;
using TestAPI.Models;
using Dapper;
namespace TestAPI.Controllers
{
public class TestAPIModelsController : ApiController
{
// GET: api/TestAPIModels
public IQueryable<TestAPIModel> Getdetails(int id)
{
OracleConnection dbConn = new OracleConnection("DATA SOURCE=AX;PASSWORD=CM;PERSIST SECURITY INFO=True;USER ID=AB");
dbConn.Open();
var strQuery = #"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER = " +id;
retrun dbConn.Query<TestAPIModel>();
dbConn.Close();
}
}
}
It throws an error saying that the dbconn.Query is not in context and I also tried TestAPIContext.Init even that throws error. Can anyone please suggest me how to deal Oracle connection with the Dapper. I am new to ASP.NET and the Creating the services. kind of really stuck, any help is greatly appreciated.
You were not passing the SQL. Also, the explicit close is not needed. You can wrap the code in a using as under the hood SqlConnection.Dispose() calls the SqlConnection.Close().
Perhaps this a typo, but "retrun" should be "return". Connectionstring should be read from the app.config vs. hard coded and I'd also consider making 'id' a parameter.
using (var dbConn = new OracleConnection("DATA SOURCE=AX;PASSWORD=CM;PERSIST SECURITY INFO=True;USER ID=AB"))
{
dbConn.Open();
var strQuery = #"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER = " +id;
return dbConn.Query<TestAPIModel>(strQuery);
}
I could handle this, with the following solution:
1. Install Oracle.ManagedDataAccess.Core Package from nuget.
2. Write ConnectionString as follows:
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=0.0.0.0)(PORT=1521))(CONNECT_DATA=(SID=sidName))); User Id=*****; Password=******;
PORT=1521 => Default port of Oracle is 1521, you can change it with your Oracle server port
0.0.0.0 => Oracle server IP or name
sidName => SidName of oracle server
3. C# snippet code:
protected IDbConnection GetChargingOracleDbConnection
{
get
{
var oracleConnection = new OracleConnection("OracleConnectionString");
oracleConnection.Open();
return oracleConnection;
}
}
var query = "SELECT Id, Name FROM Service";
using (var dbConnection = GetChargingOracleDbConnection)
{
return dbConnection.Query<MyModel>(query).ToList();
}

(are you missing a using directive or an assembly reference?)

i am writing common business logic class in App_code folder for connecting to database using EFW.but showing the following error " Error 1 The type or namespace name 'job' could not be found"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace WebApplication6.App_Code
{
public class BlCommon
{
public List<job> GetJobs()
{
pubs2012Entities pubsobject = new pubs2012Entities();
var x = pubsobject.jobs.ToList<job>();
return x;
}
}
}
and class generated by EFW from jobs table is
namespace WebApplication6.App_Code
{
using System;
using System.Collections.Generic;
public partial class job
{
public short job_id { get; set; }
public string job_desc { get; set; }
public byte min_lvl { get; set; }
public byte max_lvl { get; set; }
}
}
Seem you dont have a reference to assembly wich contain mentioned class
Ok I got it:
Public List<job> GetJobs()
{
pubs2012Entities pubsobject = new pubs2012Entities();
var x = pubsobject.jobs.ToList<job>();
return x;
}
Click on Job, Move the mouse cursor over the blue dash that appear at the bottom of
job click Generate Class and then move your Job.cs code to your new job.cs class and
delete the old one.

Reading values from DBML(having stored procedure)

I have a dbml that has stored procedures dragged off.I have EmployeeModel class that has get and set propertise .
I have an interface IEmployee and a Repository Employee Repository that has the implementation of the methods.Please refer the code.In Stored procedure GetRoles i just have SELECT * FROM ROLE .
In repository how to loop through the resultset.Can i change ISingleResult to IMultipleResult in dbml designer file?
EmployeeModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcWebsite.Models
{
public class EmployeeModel
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public string TaskMark { get; set; }
public int RoleFlag { get; set; }
}
}
IEmployee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcWebsite.Models;
namespace MvcWebsite.DAL
{
public interface IEmployees
{
IList<EmployeeModel> ListAll();
// void Save(EmployeeModel employ);
}
}
EmployeeRepository.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcWebsite.Models;
using System.Data.Linq;
namespace MvcWebsite.DAL
{
public class EmployeeRepository:IEmployees
{
private DataDataContext _dataContext;
public EmployeeRepository()
{
_dataContext = new DataDataContext();
}
public IList<EmployeeModel> ListAll()
{
//IMultipleResults result =_dataContext.GetRoleDetails();
//var Emps = result.GetResult(EmployeeModel);
List<EmployeeModel> emp = _dataContext.GetRoleDetails();
// foreach (GetRoleDetailsResult role in Emps)
// {
// role.Description=Emps.
// }
return Emps.ToList();
}
}
}
You can loop through the resultset as below:
List<EmployeeModel> employeeModels = new List<EmployeeModel>();
foreach (EmployeeModel employeeModel in _dataContext.GetRoleDetails())
{
employeeModels.Add(employeeModel);
}
Or you can use System.Linq.Enumerable class ToList<> method as below:
List<Product> products = context.GetProducts().ToList<Product>();
IMultipleResults is used when stored procedure is returning more than one result sets. However when you drop such procedures on to the designer, it doesn't generate IMultipleResults. For this you can change the designer generated code to use IMultipleResults as below:
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetCustomerAndProducts")]
[ResultType(typeof(Customer))]
[ResultType(typeof(Product))]
public IMultipleResults GetCustomerAndProducts()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((IMultipleResults)(result.ReturnValue));
}
However, it would overwrite your modifications when you do any changes in the designer because it would regenerate the code. To avoid this you can use partial classes.
Or you can also use SqlMetal tool. It is a command-line tool that generates code and mapping for the LINQ to SQL component of the .NET Framework. This tool generates IMultipleResults. You can get the details for this tool here:
http://msdn.microsoft.com/en-us/library/bb386987.aspx
Edited:
Repository functionality will be same regardless of you work in ASP.Net Mvc or WinForms or any other presentation layer.
You can change your repository function to below:
public List<EmployeeModel> ListAll()
{
return _dataContext.GetRoleDetails().ToList<EmployeeModel>();
}
Or:
public List<EmployeeModel> ListAll()
{
List<EmployeeModel> employeeModels = new List<EmployeeModel>();
foreach (EmployeeModel employeeModel in _dataContext.GetRoleDetails())
{
employeeModels.Add(employeeModel);
}
return employeeModels;
}

Why isn't my Entity Framework Code First Pluralization working?

I'm using Entity Framework Code First. Usually I have no problem, but for a database I'm working with I keep getting errors that it can't find the table in the SQL Server database. Here is what my class looks like:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class CustomApp_User
{
[Key]
public int UserID { get; set; }
[MaxLength(50)]
public string Username { get; set; }
[MaxLength(250)]
public string Email { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
In the database I have a table called "CustomApp_Users" to match the above. Note it has the "s" at the end.
And then I have:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
public class CustomAppDB : DbContext
{
public DbSet<CustomApp_User> CustomApp_Users { get; set; }
}
I expected EF codefirst to pluralize so that it would find "CustomApp_Users" in the database since this is how it usually works. But instead I get the error:
Invalid object name 'dbo.CustomApp_User'.
It appears it's not pluralizing the table name. I can't figure out why. One thing different with this database is that the Primary Keys do not follow the normal convention so I use the [Key] annotation.
I do know that if I use the [Table] annotation for my class it will work:
[Table("CustomApp_Users")]
But, I'd like to find out why the pluralization is not working the way I thought it would.
That is because the PluralizationService in EF can not pluralize it. It returns the same string if you pass it "CustomApp_User". Unfortunately you can not customize this service. So you need to configure the table name explicitly.

Resources