recover "DbContext" lost out after a method - c#

I need your help.
I begin to ASP.net and I fail to retrieve a "dbcontext" to display my request in a "datagrid". Here is my code:
public IQueryable<DiagTab> Clooper(string m_ValEnvoi)
{
string Ladatatable = m_ValEnvoi;
using (var db = new DiagEntities())
{
var secki = db.DiagTabs.Where(Ladatatable); // Ladatatabase = Dynamic LinQ
return secki;
}
I call this way (no error)
TheLoop pilou = new TheLoop();
pilou.Clooper(Valtest);
var olami = pilou.Clooper(Valtest);
but if i try this:
var selection_click = olami;
GridView1.DataSource = selection_click.ToList();
GridView1.DataBind();
the code is interrupted and displays "Could not complete the operation because the DbContext has been deleted".
Is it possible to get the paste has Dbcontext for this request?
thanks for your help

You should call ToList() inside the method, before disposing the DbContext.

Don't use using which dispose the DiagEntities and instead of it, if you want to use it in several methods just declare a property for your DiagEntities in the class constructor.
public IQueryable<DiagTab> Clooper(string m_ValEnvoi)
{
string Ladatatable = m_ValEnvoi;
var secki = db.DiagTabs.Where(Ladatatable); // Ladatatabase = Dynamic LinQ
return secki;
}

Related

Convert System.Data.Entity.DynamicProxies to (non proxy) class in C#

I am getting some data from the database and storing this in a global variable as shown:
//Global Variable
public static List<stuff> Stuff;
using (var context = new StuffContext())
{
stuff = new List<stuff>();
stuff = (from r in context.Stuff
select r).ToList();
}
The problem I am having is that the context closes and when I wish to access some of the data stored in the global variable, I cannot.
The data is of System.Data.Entity.DynamicProxies.Stuff instead of Application.Model.Stuff which means I then receive this error when I try to do something with the data:
"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."
My question is how can I, using the above code as an example, convert / cast to the type that I want so that I can use the data else where in my application?
Edit: Quick screen grab of the error:
The Solution was due to lazy loading after all.
I had to tell the query to grab everything so that when the context closes I still had access to the data.
This is the change I had to make:
public static List<stuff> Stuff;
using (var context = new StuffContext())
{
stuff = new List<stuff>();
stuff = (from r in context.Stuff
.Include(s => s.MoreStuff).Include(s => s.EvenMoreStuff)
select r).ToList();
}
Try to Disable ProxyCreationEnabled In Your Project BbContext constructor As Follow:
Configuration.ProxyCreationEnabled = false;

Insert with Linq-to-SQL sometimes fails

I have a project that inserts personal information to a table and details into another table. But sometimes personal information cannot be recorded, however details are recorded. As below code part, firstly personal information are inserted, then details. But sometimes personal information doesn't get saved and userId returns 0, So details are saved. I don't know why it doesn't work. Any idea?
public int ConferenceIdyeGoreKisiBilgileriniKaydet(string orderId)
{
KisiselBilgilerBal kisiBilgileri = (KisiselBilgilerBal)Session["kisiselBilgilerSession"];
registrationCode = GenerateGeristrationCode();
string toplamMaliyet = Session["toplamOdeme"].ToString();
PersonalInformation.SavePersonalInformations(kisiBilgileri, registrationCode,conferenceName);
int userId = AuthorPaperDetaylari.AdVeSoyadaGoreIdGetir(kisiBilgileri.f_name, kisiBilgileri.l_name);
AuthorPaperDetaylari.SaveAuthorPaperDetails(authorPaperDetay, userId); // save details via userId.
return userId;
}
This method saves personal information.
public static void SavePersonalInformations(KisiselBilgilerBal kisiBilgileri,string registrationCode,string conferenceName)
{
try
{
string cs = ConfigurationManager.AppSettings["SiteSqlServer"];
DBDataContext db = new DBDataContext(cs);
DBpersonalInformation personalInfo = new DBpersonalInformation();
personalInfo.f_name = kisiBilgileri.f_name;
personalInfo.l_name = kisiBilgileri.l_name;
personalInfo.university_affiliation = kisiBilgileri.university_affiliation;
personalInfo.department_name = kisiBilgileri.department_name;
personalInfo.address1 = kisiBilgileri.address1;
personalInfo.address2 = kisiBilgileri.address2;
personalInfo.city = kisiBilgileri.city;
personalInfo.state = kisiBilgileri.state;
personalInfo.zipCode = kisiBilgileri.zipCode;
personalInfo.country = kisiBilgileri.country;
personalInfo.phone = kisiBilgileri.phone;
personalInfo.email = kisiBilgileri.email;
personalInfo.orderId = kisiBilgileri.orderId;
personalInfo.registrationCode = registrationCode;
personalInfo.date = DateTime.Now;
personalInfo.conferenceName = conferenceName;
db.DBpersonalInformations.InsertOnSubmit(personalInfo);
db.SubmitChanges();
}
catch (Exception)
{
}
}
This method saves details
public static void SaveAuthorPaperDetails(AuthorPaperDetailsBal authorPaperDetay, int userId)
{
try
{
string cs = ConfigurationManager.AppSettings["SiteSqlServer"];
DBWebDataContext db = new DBWebDataContext(cs);
DBAuthorPaperDetail authorPaperDetail = new DBAuthorPaperDetail();
authorPaperDetail.paper_title = authorPaperDetay.paperTitleDetails;
authorPaperDetail.conference_maker_id = authorPaperDetay.confMakerId;
authorPaperDetail.additional_paper_title = authorPaperDetay.additionalPprTtle;
authorPaperDetail.areYouMainAuthor = authorPaperDetay.mainAuthor;
authorPaperDetail.feeForFirstAuthorPaper = authorPaperDetay.registerFeeForFirstAuthor;
authorPaperDetail.feeForAdditionalPaper = authorPaperDetay.regFeeForAdditionalPape;
authorPaperDetail.feeForParticipCoAuthors = authorPaperDetay.regFeeForCoAuthors;
authorPaperDetail.userId = userId;
authorPaperDetail.firstCoAuthorName = authorPaperDetay.firstCoAuthor;
authorPaperDetail.secondCoAuthorName = authorPaperDetay.secondCoAutho;
authorPaperDetail.thirdCoAuthorName = authorPaperDetay.thirdCoAuthor;
authorPaperDetail.toplamOdeme = authorPaperDetay.toplamMaliyet;
db.DBAuthorPaperDetails.InsertOnSubmit(authorPaperDetail);
db.SubmitChanges();
}
catch (Exception)
{
}
}
I don't know why it doesnt work. Any idea?
...
catch (Exception)
{
}
Well, that explains pretty much everything... don't do this. Ever. The database layer is trying to tell you what the problem is, and you are sticking your fingers in your ears, hoping that'll make it go away. If I had to guess: maybe an occasional timeout due to being blocked by another SPID.
If you can't do anything useful or appropriate with an exception, just let it bubble to the caller. If it gets to the UI, tell the user about it (or just log the issue internally and tell the user "There was a problem").
Also, a LINQ-to-SQL data-context is IDisposable; you should have using statement around db.
In addition to Marc's answer... You are calling SubmitChanges twice. If you want atomic data storage, you should call it once. You can use relational properties to create an object graph, and submit the whole graph at once.
public void SaveParentAndChildren()
{
using (CustomDataContext myDC = new CustomDataContext())
{
Parent p = new Parent();
Child c = new Child();
p.Children.Add(c);
myDC.Parents.InsertOnSubmit(p); //whole graph is now tracked by this data context
myDC.SubmitChanges(); // whole graph is now saved to database
// or nothing saved if an exception occurred.
} //myDC.Dispose is called for you here whether exception occurred or not
}

The EntityKey property can only be set when the current value of the property is null

i'm trying to execute an EF update in the following manner but continue to receive this error:
The EntityKey property can only be set when the current value of the property is null.
using (hydraEntities db = new hydraEntities())
{
YouUser = db.youusers.Include("address").Include("entity").Include("youusercontacts.contact").Include("youuserlogins").Include("youusernotes.note").Include("youusernotes.youuser.entity").Where( yu => yu.YOUUserId.Equals(YOUUserId)).First();
}
YouUser.entity.FirstName = txtFirstName.Text;
YouUser.entity.LastName = txtLastName.Text;
YouUser.address.AddressLine1 = txtAddressLine1.Text;
YouUser.address.AddressLine2 = txtAddressLine2.Text;
YouUser.address.City = txtCity.Text;
YouUser.address.State = ddlState.SelectedValue;
YouUser.address.Zipcode = txtZipcode.Text;
using (hydraEntities db = new hydraEntities())
{
db.youusers.AddObject(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
Would greatly appreciate any insight on how I can fix this and execute the statement above.
Don't use AddObject in this scenario. It is for inserting a new entity but you are updating existing one. Use Attach instead:
using (hydraEntities db = new hydraEntities())
{
db.youusers.Attach(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
In my scenario I was adding objects several times at once through different threads. I had to lock the Model Container object when doing this, to make sure only one object would be processed at once.

Save Object back to the database

I am working on a project where I am converting some VB.Net class libraries to C# libraries (mostly to learn C# syntax). My problem is that I cannot get the Save function working.
I am building my object with this:
public static StoreEmployee Create(string LoginId)
{
var emp = new StoreEmployee();
using (var dt = DAC.ExecuteDataTable("usp_ActiveEmployeeSelect",
DAC.Parameter(CN_LoginId, LoginId)))
{
emp.StoreId = Convert.ToString(dt.Rows[0][CN_StoreId]);
emp.FirstName = Convert.ToString(dt.Rows[0][CN_FirstName]);
emp.LastName = Convert.ToString(dt.Rows[0][CN_LastName]);
emp.UserName = Convert.ToString(dt.Rows[0][CN_UserName]);
emp.Role = Convert.ToString(dt.Rows[0][CN_Role]);
emp.Description = Convert.ToString(dt.Rows[0][CN_Description]);
}
return emp;
}
And then creating it with this
private static void FillStoreEmployeeObject(string empLoginId)
{
StoreEmployee.Create(empLoginId);
}
And then trying to use this save function to save the object back to the database:
public override Boolean Save(string LoginId)
{
try
{
int retVal = DAC.ExecuteNonQuery("usp_ActiveEmployeeSave",
DAC.Parameter(CN_LoginId, LoginId),
DAC.Parameter(CN_StoreId, StoreId),
DAC.Parameter(CN_FirstName, FirstName),
DAC.Parameter(CN_UserName, UserName),
DAC.Parameter(CN_Role, Role),
DAC.Parameter(CN_Description, Description));
return true;
}
catch
{
return false;
}
}
I don't get a syntax warning for that but I have revised it many times so I want to make sure that is correct before I move on. Does this look correct? By the way I am trying to call the Save function with this
StoreEmployee.Save(Convert.ToString(Login))
which gives me this error An object reference is required for the non-static field, method, or property However when I mark my function as static my Create function shows errors so I am left very confused.
Save is an instance method.
As the error message states,you need to call it on an existing instance of StoreEmployee (such as the one returned by Create).

How do I add an object to the database using Linq to SQL?

I'm trying to learn LINQ to SQL and I'm able to query the database and get back an IQueryable and manipulate the objects I retrieve from that. But I've no idea how to add a new object back into the database or into the original IQueryable.
private DataContext db;
private IQueryable<ActionType> action;
public void BuildQuery(string connection) {
db = new DataContext(connection);
action = db.GetTable<ActionType>().Select(a=>a);
ActionType at = new ActionType();
at.Name = "New Action Type";
// What now? action.add(at) || db.GetTable<ActionType>.add(at); ??
}
It's a suprisingly hard thing to search for if you don't know the right terms. And I can't find any examples that do exactly what I want them to do.
So, how do I go about adding new objects to a query/database?
To insert your newly created instance of "ActionType", you need add your object to the data context (and "add" was renamed to "InsertOnSubmit" during Linq-to-SQL beta) and then call SubmitChanges on the data context:
public void BuildQuery(string connection) {
db = new DataContext(connection);
action = db.GetTable<ActionType>().Select(a=>a);
ActionType at = new ActionType();
at.Name = "New Action Type";
// What now? action.add(at) || db.GetTable<ActionType>.add(at); ??
db.ActionTypes.InsertOnSubmit(at);
db.SubmitChanges();
}
See this blog post here why you should be using InsertOnSubmit over Attach.
Marc
private DataContext db;
private IQueryable<ActionType> action;
public void BuildQuery(string connection) {
db = new DataContext(connection);
action = db.GetTable<ActionType>().Select(a=>a);
ActionType at = new ActionType();
at.Name = "New Action Type";
//There must be a table like ActionType and it seems ActionTypes when calling it ith // db
db.ActionTypes.InsertOnSubmit(at);
db.SubmitChanges();
}
You can see a nice example here : Click Here
Now all you need to do is submit your changes back to the database:
db.Attach(at);
db.SubmitChanges();
I'd wrap the DataContext within a using statement - it ensures it is disposed of, when the operation is complete.
Like this:
public void BuildQuery(string connection)
{
using (var db = new DataContext(connection))
{
action = db.GetTable<ActionType>().Select(a=>a);
ActionType at = new ActionType();
at.Name = "New Action Type";
// What now? action.add(at) || db.GetTable<ActionType>.add(at); ??
db.ActionTypes.InsertOnSubmit(at);
db.SubmitChanges();
}
}

Categories

Resources