how to use the stored procs using petapoco - petapoco

I have created a stored procedure in data base.
var db = new PetaPoco.Database("connection name");
return db.Query<sppoco>("exec spstp");
I declared a spppoco.cs in models with the column names I used in stored procedure
public class spppoco
{
public int rid { get; set; }
public string name { get; set; }
public int Address { get; set; }
}
But when I am executing I am getting an error like Invalid object name 'sppoco'.

That's easy! It's just a typo.

Related

ASP.NET Core and EF Core 1.1 - Display data using Stored Procedure

I have problem with my query. I want to display the result on a view.
[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index()
{
return View(await _Context.Employee
.FromSql("EXEC sp_GetLoanDetails")
.ToArrayAsync());
}
Here is my list of items I want to view:
public class StoredProcRow
{
[Key]
public int empID { get; set; }
public string empFullName { get; set; }
public double EducationalLoan { get; set; }
public double PettyCash { get; set; }
public double BusinessLoan { get; set; }
public double ApplianceLoan { get; set; }
public double EmergencyLoan { get; set; }
public double AllPurposeLoan { get; set; }
public double KAPUSOIILoan { get; set; }
public double FiestaLoan { get; set; }
public double SalaryLoan { get; set; }
public double Pledge { get; set; }
public double PagIbigLoan { get; set; }
public double SSSLoan { get; set; }
public double AllAroundLoan { get; set; }
public double Total { get; set; }
}
Note: These entities name are the same as entities on column name in sp_GetLoanDetails
Is this achievable right now on EF Core 1.1? Or do I need to go back to manual ADO.NET code?
Thanks!
While support for stored procedures isn’t completely there with Entity Framework Core yet, you still can use FromSql to consume stored procedures with it.
In order to do that, the database context needs to know the entity you are mapping to from the stored procedure. Unfortunately, the only way to do that right now is to actually define it as an entity in the database context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<StoredProcRow>(entity =>
{
// …
});
}
Then, you can consume the stored procedure by running the FromSql method on a set for that entity:
public virtual IQueryable<StoredProcRow> GetLoanDetails()
{
return Set<StoredProcRow>().FromSql("[sp_GetLoanDetails]").AsNoTracking();
}
Note that I’m using a AsNoTracking here to avoid the data context to track changes to entities that come from the stored procedure (since you don’t have a way to update them anyway). Also I’m using Set<T>() inside the method to avoid having to expose the type as a member on the database context since you cannot use the set without the stored procedure anyway.
Btw. you don’t need (not sure if that even works) EXEC in the sql statement you pass to FromSql. Just pass the stored procedure name and any arguments to it, e.g.:
Set<MyEntity>().FromSql("[SomeStoredProcedure]");
Set<MyEntity>().FromSql("[SProcWithOneArgument] #Arg = {0}");
Set<MyEntity>().FromSql("[SProcWithTwoArguments] #Arg1 = {0}, Arg2 = {1}");
From NuGet add System.Data.Common and System.Data.SqlClient. These allow ADO.NET commands to be run i.e. a stored procedure.
https://forums.asp.net/post/6061777.aspx

Querying data from a child table in .Net Mobile service

I have two simple models in .net backend based Azure Mobile Service Project, as shown below & I am not able to query the child table (querying parent table, UserItem, works just fine)
(The Id is nvarchar(128) & is autogenerated as newId by DB)
public class AnswerItem: EntityData
{
public string Content { get; set; }
public UserItem By { get; set; }
public QuestionItem ForQuestion { get; set; }
public double Rating { get; set; }
public string Comment { get; set; }
}
& a child to this UserItem Table as shown below
public class QuestionItem: EntityData
{
public string Content { get; set; }
public bool IsAnswered { get; set; }
public int NumberOfAnswers {get; set;}
public UserItem By { get; set; }
public string ById { get; set; }
public string AtLocation { get; set; }
}
As you notice, the QuestionItem has a FK relationship to UserItem table on ById field (Referencing Id field in UserItem Table)
The issue is I am getting a Bad Request error when I try to query the data from child table
Following are some queries that I tried
private IMobileServiceTable<QuestionItem> questionTable = App.MobileService.GetTable<QuestionItem>();
questions = await questionTable.Where(x=>x.IsAnswered==true).ToCollectionAsync(); (Does not Work)
questions = await questionTable.Where(x=>x.ById="UserIdGoesHere").ToCollectionAsync(); (Does Not Work)
questions = await questionTable.Where(x=>x.Content.StartsWith("q")).ToCollectionAsync(); (This Works)
questions = await questionTable.ToCollectionAsync(); (This Works as well)
If I fire a TSQL query in Sql Server Object explorer they all return correct values.
I am at my wits end on what could be wrong with my approach.
Any help is really appreciated.
Thanks
Supreet
Investigating further the Request it was generating was like this
192.168.2.4:50002/tables/QuestionItem?$filter=(byid eq 'myUniqueGuId')
analyzing fiddler output shows this error
"The query specified in the URI is not valid. Could not find a property named 'byid' on type 'x2Service.DataObjects.QuestionItem'"
Off course there is no fields in the table by the name of 'byid' the one I have is called 'ById' Its the JsonProperty adorner that changed it [JsonProperty(PropertyName = "byid")] In my client class.
Removed the Json Property & it worked just fine

Identity Column Inserting Null With MVC Code First

I am using MVC to generate my database. I have the following code structure in my UserProfile class:
[KeyAttribute()]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
This generates the database fine, but when I try to insert a record it says UserId cannot be null. I cannot figure out why it isn't auto generating an Id integer.
This was because I had some issues updating the database. Needed to manually drop this table and re-create it. Is working fine now.

NHibernate - IUserType For Changing Type?

My application has the following classes:
public class Widget {
public virtual int Id { get; set; }
public virtual WidgetType Type { get; set; }
public virtual string Parameters { get; set; }
}
public class WidgetType {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string ParametersAssembly { get; set; }
public virtual string ParametersClass { get; set; }
}
Now if i'd like to update the Parameters for a particular widget i would say something like:
// Get the widget
var widget = GetWidget(1);
// Create an instance of the type parameters class
var parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/"
+ widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
... Code here to update the parameters
widget.Parameters = new XmlSerializer(parameters.GetType()).Serialize(parameters);
I have to do the reverse when i wish to get the parameters. You can imagine this becomes quite tedious. I was wondering if it was possibly to automatically do this?
I've been looking at the IUserType interface. I found an article which is kind of similar. However my problem is a little more complicated as my type changes based on the type of the widget.
I'd appreciate it if someone could let me know if this is possible and possibly how it could be achieved. Thanks
an easy way
public class Widget
{
public virtual int Id { get; set; }
public virtual WidgetType Type { get; set; }
private string _serializedParameters;
private virtual string SerializedParameters {
get
{
return new XmlSerializer(Parameters.GetType()).Serialize(Parameters);
}
set
{
_serializedParameters = value;
// code to deserialize the Parameters and set to Parameters
var ptype = Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass);
Parameters = Activator.CreateInstance(ptype);
}
}
private object _parameters;
public virtual object Parameters
{
get
{
if (_parameters == null)
_parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
return _parameters;
}
set { _parameters = value; }
}
}
it can't be in the Parameters property because then you have to get -> alter -> set instead of get -> alter. But you are right that building the parameters object should go in the getter of Parameters because only there we can be sure to have the WidgetType loaded
it is essentially the same as a UserType except that we know that WidgetType is there

PetaPoco to return self-referencing hierarchy

How would one write a query/method to return a POCO that is from a self-referencing database as shown in this question
Firstly you would map it a flat class. eg. db.Fetch<CategoryDb>("select * from categories");
public class CategoryDb {
public int Id { get; set; }
public string Name { get; set; }
public int ParentCategoryId { get; set; }
}
From here I would then create a new Object that self referenced itself. (You could use the existing object with the ParentCategory having the [Result] attribute on it.)
public class Category {
public int Id { get; set; }
public string Name { get; set; }
public Category ParentCategory { get; set; }
}
You could then take this and convert your flat list into a nested list.
I do have code somewhere that can do this, and for which it also provides searching methods etc, but its not on this computer. I will update tomorrow with a link to the code.