Can't populate database table - c#

protected void ButtonAddDatabase_Click(object sender, EventArgs e)
{
using (KnowItCvdbEntities db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmplDbSkill = (
from p
in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
_emp = theEmplDbSkill;
if (_emp != null)
{
foreach (var vItem in ListBoxDatabases.Items)
{
if (ValueAlreadyInListDb(vItem))
return;
}
//Get existing skilllevel from db
var skillLevel = (from sL in db.TECHNICAL_SKILL_LEVEL
where sL.technical_skill_level_id == Convert.ToInt32(DropDownListDB.SelectedValue)
select sL).FirstOrDefault();
//Get existing skillvalue from db
var skillValue = (from sV in db.TECHNICAL_SKILLS
where sV.technical_skill_id == Convert.ToInt32(RadioButtonListDatabase.SelectedValue)
select sV).FirstOrDefault();
//Adding to employees_technical_skills table
var empSkill = new EMPLOYEES_TECHNICAL_SKILLS
{
technical_skill_id = Convert.ToInt32(DropDownListDB.SelectedItem.Value),
TECHNICAL_SKILLS = skillValue,
technical_skill_level_id = Convert.ToInt32(RadioButtonListDatabase.SelectedItem.Value)
TECHNICAL_SKILL_LEVEL = skillLevel,
employee_id = _emp.employee_id
}
_emp.EMPLOYEES_TECHNICAL_SKILLS_Add(empSkill);
db.SaveChanges();
_emp.EMPLOYEES_TECHNICAL_SKILLS.Add(empSkill);
db.SaveChanges();
}
}
}
Right now I'm working on populating the following table:
This is my tables:
But I keep getting the error:
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
Regards,
Kristian.

It looks like the Entity framework can't convert Convert.ToInt32() to an SQL expression. I would convert the radiobutton and dropdown values to int in memory first, then pass them to the queries:
int TechnicalSkillLevelID = int.Parse(DropDownListDB.SelectedValue);
int TechnicalSkillID = int.Parse(RadioButtonListDatabase.SelectedValue);
//Get existing skilllevel from db
var skillLevel = (from sL in db.TECHNICAL_SKILL_LEVEL
where sL.technical_skill_level_id == TechnicalSkillLevelID)
select sL).FirstOrDefault();
//Get existing skillvalue from db
var skillValue = (from sV in db.TECHNICAL_SKILLS
where sV.technical_skill_id == TechnicalSkillID)
select sV).FirstOrDefault();
//Adding to employees_technical_skills table
var empSkill = new EMPLOYEES_TECHNICAL_SKILLS
{
technical_skill_id = skillValue.technical_skill_id,
TECHNICAL_SKILLS = skillValue,
technical_skill_level_id = skillLevel.technical_skill_level_id)
TECHNICAL_SKILL_LEVEL = skillLevel,
employee_id = _emp.employee_id
}
Also, since you already pulled back the skill levels and skill values, no need to grab the values from the drop down / radio button list. Just use the skillValue and skillLevel objects.

Related

How to return list of object which associated with one ID?

I am still getting familiar with SQL and LINQ and I am trying to get every objects and its objects which is under one ID.
The below is the EDMX Diagram.
I am passing ClientID and I want to list everything that is under that ClientID and the below is my query to do so but as you can see query is only returning the first element but how to change it to return the list of every elements as below:
Passed ClientID
THeaderTitle 1
TReportName 1
TReportName 2
MY query is below which is returning the first element:
public TReportHeaderModel GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
}).First();
return query;
}
}
I've got it working!
I had to change it in my interface as
IList GetHeadersByClient (int ClientID);
So that I can return List of elements in my controller to pass to view.
public IList<TReportHeaderModel> GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
});
return query.ToList();
}
}

Populate a view model with a data model with a method aswell

i need to populate my articles ViewModel with a model that has the database data in it, but i have a method that i need to assign to one of my properties
The list of images is the property that needs the method on it.
The method is called once for every item in the list of articles.
Here is my code:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
}).ToList();
articleViewModel.Images = imageService.GetImagesForArticle(articlemodel.Id.ToString());
return View(query);
}
I have also tried putting the method inside the linq:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
Images = imageService.GetImagesForArticle(a.Id.ToString())
}).ToList();
return View(query);
}
it throws an exception of:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[New_MinecraftNews_Webiste_MVC.Models.ImageInfo] GetImagesForArticle
I added a foreach loop at the end insted of anything else and it works:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var modelList = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName
}).ToList();
foreach (var model in modelList)
{
model.Images = imageService.GetImagesForArticle(model.Id.ToString());
}
return View(modelList);
}

cant display the result linq to sql

I have written a WPF program with c# that uses a SQL server database
here are my tables
the goal when the user checks the radiobutton, a listview named lv_factors shows the sell factors that are sold by check.
here is the code:
private void rb_sell_Checked(object sender, RoutedEventArgs e)
{
var db = new mydataDataContext();
var all = from p in db.tb_sellFacts
from r in db.tb_Clients
from s in db.tb_sellChecks
from t in db.tb_banks
from q in db.tb_checkStatus
where p.id_sellFact == s.id_sellfact &&
r.id == p.id_customer &&
t.id == s.id_bank &&
q.id == s.passed
select new dataTypes.AllChecks
{
bankname = t.name.ToString(),
id = p.id_sellFact.ToString(),
buydate = p.buydate,
checkaccount = s.checkaccount,
checkfee = s.paidprice.ToString(),
checknumber = s.checknumber,
checkstate = q.status,
custId = p.id_customer.ToString(),
idbank = s.id_bank.ToString(),
insertdate = p.insertdate,
passed = q.id.ToString(),
checkDate = s.checkdate,
CustName = r.family
};
lv_factors.ItemsSource = all;
}
but the listview doesn't show anything.can anyone help me?
didnt get you exception by this query ? you must get exception, .ToString() can not be called in linq queries, it cant be converted to expression tree. i posted ( here ) an answer says what can be called on linq queries.

Populating textboxes using LINQ2SQL

In my web forms, I have text boxes and one radiolist which I need to populate through a LINQ2SQL query. So far I coded this query to fetch particular records which is going to be populated into the DB.
using (dbTestDataContext db = new dbTestDataContext())
{
var query = from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
};
};
Now I know that the record which this query is going to be fetching is gonna be only 1 unique record. I want to show the record in these textboxes and select that radio button:
tbName
tbNum
tbAcctNum
rbtnCorpAcct
How should I do this? Thank you in advance!
Very simply:
using (dbTestDataContext db = new dbTestDataContext())
{
var query = (from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
}).FirstOrDefault();
if (query != null)
{
tbName.Text = query.Name;
tbNum.Text = query.Num;
//and so on
rbl.SelectedValue = query.SomeValue;
}
};
Same as others have answered with addition of radio button:
tbName.Text = query.Name;
tbNum.Text = query.Num;
tbAcctNum.Text = query.AcctNum;
if(query.CorpAcct)
rbtn.SelectedValue = "Yes"; \\Where "Yes" is one of the radio button values
else
rbtn.SelectedValue = "No";
\\Could also use SelectedIndex, rbtn.SelectedIndex = 0 or 1
Try the following:
using (dbTestDataContext db = new dbTestDataContext())
{
var query =
(
from r in db.Table1
where r.Code == getCode
select new
{
//Account Info
r.Name,
r.Num,
r.AcctNum,
r.CorpAcct, //Bool
}
).FirstOrDefault();
tbName.Text = query.Name;
....
};
The first thing you need to do is retrieve a single result from your query. As you have it written, you are returning an IQueryable object which is now stored in the variable "query"
To get a single object, do this
var myObject = query.SingleOrDefault();
Then you can access the individual properties of that object and assign them like this
tbName.Text = myObject.Name

Updating through LINQ in different DataBase

I have a DB which looks like this:
1st:
CommissionsV2 (Table = Entity_Product_Point)
This is my DBML too which has only one table.
2nd:
WebEnroll (Table = PlanMaster)
This is my another DBML which has one table in it.
Now through LINQ I am adding a row in this which has a query like this:
CommissionsV2DataContext cv = new CommissionsV2DataContext();
Entity_Product_Point ev = new Entity_Product_Point();
ev.Entity_ID = getEntity;
ev.Product_ID = tr.First();
ev.HiCommissionOld = (double)firststYrComp;
ev.LowCommissionOld = (double)recurringComp;
ev.HiCommission = (double)finalFirstYrComp * 100;
ev.LowCommission = (double)finalRecurringComp * 100;
ev.DateCreated = System.DateTime.Now;
cv.Entity_Product_Points.InsertOnSubmit(ev);
cv.SubmitChanges();
Now my update statement is like this:
protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Getting the Entity_ID from the Session!
int getEntity = Int16.Parse(Session["EntitySelected"].ToString());
//Accessing the variables from the controls!
System.Web.UI.WebControls.TextBox product_ID = gvShowComm.Rows[e.RowIndex].FindControl("ProductName") as System.Web.UI.WebControls.TextBox;
System.Web.UI.WebControls.TextBox planName = gvShowComm.Rows[e.RowIndex].FindControl("PlanName") as System.Web.UI.WebControls.TextBox;
System.Web.UI.WebControls.TextBox hiCommOld = gvShowComm.Rows[e.RowIndex].FindControl("HiComm") as System.Web.UI.WebControls.TextBox;
System.Web.UI.WebControls.TextBox lowCommOld = gvShowComm.Rows[e.RowIndex].FindControl("LowComm") as System.Web.UI.WebControls.TextBox;
//Storing the values into variables!
int product = Int16.Parse(product_ID.Text);
string plan = planName.Text;
int hiOld = Int16.Parse(hiCommOld.Text);
int lowOld = Int16.Parse(lowCommOld.Text);
//Updating the values into the table through LINQ!
dbWebEnrollDataContext dt = new dbWebEnrollDataContext(); //This has PlanName in PlanMaster Table.
CommissionsV2DataContext cv = new CommissionsV2DataContext(); //Entity_Product_Point has all the other columns which needs to be updated!
Entity_Product_Point ev = cv.Entity_Product_Points.Single(c => c.Product_ID == product);
ev.HiCommissionOld = hiOld;
ev.LowCommissionOld = lowOld;
ev.Entity_ID = getEntity;
cv.SubmitChanges();
In order to update, you need to retrieve the entity that needs to be updated.
So in your case it would be:
Entity_Product_Point ev = cv.Entity_Product_Points.Single(c => c.Product_ID == product);
ev.HiCommissionOld = hiOld;
ev.LowCommissionOld = lowOld;
// Retrieve the plan that needs to be updated and set the name
// Submit the changes
cv.SubmitChanges();
// Retrieve the new values and rebind the gridview against the new values

Categories

Resources