Why showing it is null parameter? - asp.net

I have wrote this code to see details in details view with petapoco. but it is not showing any data and it also showing null parameter. I have added and details view page.. here my database name FCBook and table is RMReceive and primary key is RrId.. please help to run this code successfully...
public ActionResult Details(int id)
{
var db = new PetaPoco.Database("FCBook");
var rmr = db.Single<RMReceive>("select * from RMReceive where RrId= #0",id);
return View(rmr);
}

You are using an expression here, your query probably won't work with raw SQL, try
var rmr = db.Single<RMReceive>(x => x.RrId == id);

Related

Panel using stored procedure - Code not reacting as expected

I have hit a small issue and hoping someone might be able to assist. I am using a panel - On the page load, it should list all the products as no category has been selected as per stored procedure (this works perfectly).
When a user clicks on a specific category, it should only show the products that have the specific CategoryID. When I run the code in SQL, it works a dream for this part too, so assume the stored procedure is ok.
At
CategoryID = CategoryID
in GetProducts, I get
Warning: Assignment made to same variable; did you mean to assign something else?
However I am following a tutorial video and this works fine. Is there another silly error that is preventing it from working?
I think I have included all the required code - sorry if its a bit overkill!!
Thanks as ever in advance - Jack
Code behind pnlCategories:
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart();
{
CategoryID = CategoryID;
};
Error identified - additional ";" added at following line:
ShoppingCart k = new ShoppingCart();
Code now reads
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
and functions as expected!
that looks like a c# error and not a SQL Server error.
The problem is here in your GetProducts method. CategoryID = CategoryID;
C# is case sensitive. If you check your tutorial carefully, one of these will probably be lower case. Make sure you type that carefully.
try code change below and see where the compiler complains.
CategoryID = categoryID;
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart();
{
CategoryID = CategoryID;
};
dlProducts.DataSource = null;
dlProducts.DataSource = k.GetProdcuts();
dlProducts.DataBind();
}

How to improve ASP.NET MVC3 app data query performance?

There is a book management system web application based on ASP.NET MVC3. When click the book index page, data query is very slow and user has to wait for several seconds for response. The code of Action Index in BookController below:
public ViewResult Index(string sortOrder, int? page)
{
ViewBag.NameSortParam = string.IsNullOrEmpty(sortOrder) ? "desc" : "";
ViewBag.CurrentSort = sortOrder;
BookModel books = from b in db.Books select b; // db = new BookContext();
switch (sortOrder) {
case "desc":
books = books.OrderByDescending(b => b.Name);
break;
default:
books = books.OrderBy(b => b.Name);
break;
}
int pageSize = 15;
int pageNumber = (page ?? 1);
return View(books.ToPagedList(pageNumber, pageSize));
}
In my opinion, the main reason of slow is that server does not response to client until all data are ready. This process takes much time.
I do not know how to solve this problem, is there any method to improve data query performance in this case? Thank you!
update:
backend database is SQL Server Compact Edition 4.0
UPDATE
I update my logic code below, orderby is used before skip and take statements. Everything goes well. Thank you all for help.
books = (from b in db.Books
orderby b.Name descending
select b)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
You are loading in all your books before filtering the dataset to just the data you need (by using ToPagedList). Change your query and use the Skip and Take methods instead of ToPagedList.
Put index on the Books.Name column (with included columns: include those which are needed in your list), on the C# side query only the filed you are needed:
books.Select(x => new {
x.Name,
x.Author,
x.Description,
x.ID }).ToPagedList(/*....*/)./*...*/)
And i would look after the ToPagedList implementation.
Use OutputCaching on the method, varying by the two parameters. An overview of this is detailed here.
[OutputCache(Duration=60,VaryByParam="sortOrder;page;")]
public ViewResult Index(string sortOrder, int? page)

How to create a LINQ or Entity SQL query to get record from a Table where Table Name is achieved at runtime

My application is in Asp.net MVC3 coded in C#.Net.
I have a view which has a DropDownList.This dropdownlist has the Name of all the Tables that are present in my database.
My requirement is when the user selects a particular Table from the Dropdownlist then thru Json im passing the Name of the table to a Json method as is shown in the below Code.
$("#MyTableNames").change(function () {
$("#MyDiv").load("/../MyController/MyActionMethod", { TableName:$("#MyTableNames").val() }, function () {
});
});
Above is how im passing my table name to my Action in the controller.
Till here all is fine.
Below is my Action Code.
I have tried Two methods to write a query...It includes the Entity SQL aswell.No LINQ as LINQ doesnt support this.
//First Method
public ActionResult MyAction(string TableName)
{
var model = db.ExecuteStoreQuery<TableName>("Select * from " + TableName + " where Delete_Flag='" + false + "'");
ViewBag.MyData=model;
return PartialView();
}
//Second Method
public ActionResult GetRecords(string TableName)
{
var sql = "SELECT VALUE emp FROM " + TableName + " AS emp ";
var query = db.CreateQuery <TableName>(sql);
Viewbag.MyData=query;
return PartialView();
}
But none of the above methods working as <>want the parameter as the table...
I want to pass the result of the query to the VierwBag so that i can populate it in the View.
Suggest how can i achieve this.
Since you don't know the type to use during design time, it would be difficult to use strongly typed generics.
Another approach would be to using ExpandoObject\dynamic with micro ORM frameworks such as Massive to query data. The data returned in this case is a ExpandoObject, which if required can be returned back to client.

Error while updating Database record with Entity Framework on ASP.NET MVC Page

I have an ASP.NET Page that updates registered User Address Details for a selected record.
Below is the update method that I am calling from my controller.
When I am calling the ApplyPropertyChanges method, I am getting an error. Did anyone run into the same error while updating the record with Entity Framework?
Appreciate your responses.
Error message:
The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state.
My Update method:
[HttpPost]
public bool UpdateAddressDetail([Bind(Prefix = "RegUser")] AddressDetail regUserAddress, FormCollection formData)
{
regUserAddress.AD_Id = 3;
regUserAddress.LastUpdated = HttpContext.User.Identity.Name;
regUserAddress.UpdatedOn = DateTime.Now;
regUserAddress.AddressType = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "Primary";
regUserAddress.Phone = ((AddressDetail)Session["CurrentAddress"]).Phone;
regUserAddress.Country = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "USA";
miEntity.ApplyPropertyChanges(regUserAddress.EntityKey.EntitySetName, regUserAddress);
miEntity.SaveChanges();
return true;
}
The error is the object is detached from the context, and ApplyPropertyChanges thinks the object is added because it isn't attached. So you would need to query from the data context or get an attached form and then apply the changes then.
HTH.
What Dave Said
+
You need to Attach() the disconnected entity to your object context:
http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx
miEntity.Attach(regUserAddress);
miEntity.SaveChanges();
Just add the following code before miEntity.SaveChanges():
miEntity.Entry(regUserAddress).State = EntityState.Modified;
First select the record (object entity), search by key through the ObjectContext. For example if the search ArticleSet EntitySet called for there to record, and once you get it modified its properties with new values and then call SaveChanges() of ObjectContext.
Example:
ObjectQuery<Article> myArt=Context.ArticleSet.Where myArt = (row => row.ArticleId == value);
myArt.Description=" new value ";
etc. ..
etc ...
Context.SaveChanges ();

Returning a column from a linked table in LINQ to SQL

My problem is that I am trying to return a simple query that contains an object Story. The Story object has a UserId in the table which links to aspnet_users' UserId column. I have created a partial class for Story that adds the UserName property since it does not exist in the table itself.
The following query gets all stories; however, a pagination helper takes the query and returns only what's necessary once this is passed back to the controller.
public IQueryable<Story> FindAllStories(){
var stories = (from s in db.Stories
orderby s.DateEntered descending
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
}
);
return stories;
}
When the helper does a .count() on the source it bombs with the following exception:
"Explicit construction of entity type 'MyWebsite.Models.Story' in query is not allowed."
Any ideas? It's not a problem with the helper because I had this working when I simply had the UserName inside the Story table. And on a side note - any book recommendations for getting up to speed on LINQ to SQL? It's really kicking my butt. Thanks.
The problem is precisely what it tells you: you're not allowed to use new Story as the result of your query. Use an anonymous type instead (by omitting Story after new). If you still want Story, you can remap it later in LINQ to Objects:
var stories = from s in db.Stories
orderby s.DateEntered descending
select new
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
};
stories = from s in stories.AsEnumerable() // L2O
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
...
};
If you really need to return an IQueryable from your method and still need the Username of the user you can use DataContext.LoadOptions to eagerload your aspnet_user objects.
See this example.

Resources