Add objects to session - asp.net

I need some clarity about session and how to add objects, because I think I do it the wrong way.
First I create a session to hold a list of Products:
Session["ShoppingCart"] = new List<Products>();
To add Products to the list, I do like this:
Session["ShoppingCart"] = new Products { ID = productId, Name = name };
I guess this isn't the right way?

I guess this isn't the right way?
Yes, this isn't the right way (please skip towards the last paragraph of my answer to know the correct way - which is not to use ASP.NET session at all). The correct way is to first get the object you stored inside the session by trying it to cast it to the same .NET type yo uhave stored inside the session:
var products = Session["ShoppingCart"] as List<Products>;
and then if this item is not null add the corresponding product to the list. We should of course make the necessary type check that the session actually contained a value with the specified key and that this value is of the expected type:
if (products != null)
{
var product = new Products { ID = productId, Name = name };
products.Add(product);
}
Of course we are using object references here which will only work if you are storing your session in-memory (sessionState mode = InProc) which of course is absolutely a terrible disaster and something you should never do in production. In a production environment you are probably persisting your session in a session server or even SQL server, aren't you? In this case it is more than obvious that working with object references is a recipe for disaster. So in this case once you have added the new product to the session you should of course set back the new list value to the session which will serialize the object instance to the corresponding data store:
if (products != null)
{
var product = new Products { ID = productId, Name = name };
products.Add(product);
Session["ShoppingCart"] = products;
}
Now, after all this being said I must admit that using ASP.NET Session is probably the huge mistake you would ever commit in a real world application. So basically every time you are using Session["xxx"] you are doing it wrong. Simply search the entire solution for the Session keyword and just get rid of it.

In order to add itens to an existing list on the Session, you must first retrieve the list then add the object to it. Here's an example:
Session["ShoppingCart"] = new List<Products>();
List<Products> productsList = (List<Products>)Session["ShoppingCart"];
productsList.add(new Products { ID = productId, Name = name });
Session["ShoppingCart"] = productsList;

Related

Removing item from list in EF model

I'm using Entity Framework and I am trying to remove a NinjqEquiment from a list belonging to an instance of Ninja.When I retrieve the list of Ninjas,I make sure to include the equipment list, so I know they are there. Then I remove the equipment from the Ninja and try to save changes. I get the following error -
The entity type List`1 is not part of the model for the current
context.
using (var db = new NinjaDbContext())
{
//get ninjas with equipment included
var ninjas = GetAllNinjas();
//get ninja
var ninja = (from n in ninjas
where n.Id == id
select n).FirstOrDefault();
//get equipment
var eq = (from e in ninja.EquipmentOwned
where e.Id == removeEqId
select e).FirstOrDefault();
//remove eq from ninja
ninja.EquipmentOwned.Remove(eq);
//Make sure entity knows EquipmentOwned has been modified
db.Entry(ninja.EquipmentOwned).State = EntityState.Modified;
//save ninja
db.SaveChanges();
}
Just remove this:
//Make sure entity knows EquipmentOwned has been modified
db.Entry(ninja.EquipmentOwned).State = EntityState.Modified;
This causes the error.
EquipmentOwned is a List<Equipment>. It is not an Entry in EF terms so it is not tracked directly by it.
When you delete an entity from such collection, EF knows that there won't be any relationship between this particular ninja and this particular equipment. It won't delete equipment from database because other ninjas may use this equipment.
To delete it completely you should remove this equipment from corresponding DbSet<> like this:
using (var db = new NinjaContext())
{
//db.Equipment is a DbSet<Equipment>
//id is PrimaryKey of Equipment table
var eq = db.Equipment.Find(id);
db.Equipment.Remove(eq);
db.SaveChanges();
}

How does Entity Framework decide whether to reference an existing object or create a new one?

Just for my curiosity (and future knowledge), how does Entity Framework 5 decide when to create a new object vs. referencing an existing one? I might have just been doing something wrong, but it seems that every now and then if I do something along the lines of:
using (TestDB db = new TestDB())
{
var currParent = db.Parents.Where(p => p.Prop == passedProp).FirstOrDefault();
if(currParent == null) {
Parent newParent = new Parent();
newParent.Prop = passedProp;
currParent = newParent;
}
//maybe do something to currParent here
var currThing = db.Things.Where(t => t.Prop == passedPropTwo).FirstOrDefault();
currThing.Parent = currParent;
db.SaveChanges();
}
EF will create a new Parent in the database, basically a copy of the currParent, and then set the Parent_ID value of currThing to that copy. Then, if I do it again (as in, if there's already two of those parents), it won't make a new Parent and instead link to the first one. I don't really understand this behavior, but after playing around with it for a while something like:
using (TestDB db = new TestDB())
{
var currParent = db.Parents.Where(p => p.Prop == passedProp).FirstOrDefault();
if(currParent == null) {
Parent newParent = new Parent();
newParent.Prop = passedProp;
currParent = newParent;
}
//maybe do something to currParent here
var currThing = db.Things.Where(t => t.Prop == passedPropTwo).FirstOrDefault();
currThing.Parent = db.Parents.Where(p => p.ID == currParent.ID).First();
db.SaveChanges();
}
seemed to fix the problem. Is there any reason this might happen that I should be aware of, or was there just something weird about the way I was doing it at the time? Sorry I can't be more specific about what the exact code was, I encountered this a while ago and fixed it with the above code so I didn't see any reason to ask about it. More generally, how does EF decide whether to reference an existing item instead of creating a new one? Just based on whether the ID is set or not? Thanks!
If your specific instance of your DBContext provided that specific instance of that entity to you, then it will know what record(s) in the database it represents and any changes you make to it will be proper to that(those) record(s) in the database. If you instantiate a new entity yourself, then you need to tell the DBContext what exactly that record is if it's anything but a new record that should be inserted into your database.
In the special scenario where you have multiple DBContext instances and one instance provides you this entity but you want to use another instance to work with and save the entity, then you have to use ((IObjectContextAdapter)firstDbContext).ObjectContext.Detach() to orphan this entity and then use ((IObjectContextAdapter)secondDbContext).ObjectContext.Parents.Attach() to attach it (or ApplyChanges() if you're also editing it - this will call Attach for you).
In some other special scenarios (your object has been serialized and/or you have self-tracking entities), some additional steps may be required, depending on what exactly you are trying to do.
To summarize, if your specific instance of your DBContext is "aware" of your specific instance of an entity, then it will work with it as if it is directly tied to that specific row in the database.

Problems while trying to retrieve value from arraylist stored in session

Please help me. Here is my code
ArrayList arrValues = new ArrayList();
arrValues = (ArrayList)Session["ArrValues"];
string CustName, Addr1, Addr2, City, State, Country, Pin, Email,Order,CustToken;
string SName, SAddr1, SAddr2, SCity, SState,SPin, SCountry;
CustName = arrValues[1].ToString().Trim();
It is thrwoing a "NullReference excption" while trying to get the value of CustName from the arraylist stored in the session. Below is the link to see the video
http://www.talash.com/testingvideo/2011-03-18_0958_Payment_Gateway_Problem.swf
The problem is that your session variable doesn't exist.
arrValues is null. You need to look into why you are loosing your session variable.
Are you trying to get this value from within a page or a module?
If you work with HttpModule the session is not available at all times and it might be that the session object is null.
since your session variable is not set to any value previously thats why u are getting an error.make this code safe by putting it inse something like this..
if(Session[Arrvalues"]!=null)
{
//your block of code//
}
else
{
Response.Redirect("to_the_page_where_this_session_variable_is_set.aspx");
}

Assign Business entity to hidden variable

Say for example if I have a business entity -> Customer, which has customerId, customerName and customerType. I have created an asp:Hidden Variable hdnCustomer to runat="server"
If I wanted to serialize the value of the customer business entity (in the code behind) to the hdnCustomer then how would I do that? Also once serialized how would I deserialize it?
// Pseudo code
Collection<Customer> customerList = new Collection<Customer>();
customerList = BusinessAccess.GetCustomerList();
hdnCustomer = serialize and assign the value of 'customerList' to hdnCustomer;
...
...
// Later on a select index change of one of the drop down lists
Inside the event handler for the drop down list:
{
Collection<Customer> customerList = new Collection<Customer>();
customerList = deserialize the value from hdnCustomer
int a = Convert.ToInt32(ddlDropDown.SelectedValue);
foreach(a in customerList)
{
// Do something
}
}
You can serialise to and from XML using XmlSerializer:
http://support.microsoft.com/kb/815813
However, if you just store the object in the ViewState[] collection that should work better:
ViewState["Customer"] = customerList;
It does the same thing: store the serialisable object in the page, hidden from the user: but it won't be in a human-readable format.
(edit: To deserialise, just get the value of ViewState["Customer"], checking for a null before using it!)
edit 2: a useful link about storing objects in ViewState:
http://www.beansoftware.com/ASP.NET-Tutorials/ViewState-In-ASP.NET.aspx
Hope that helps.
I think .net has already providing some classes to do so, look at this example

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