Populating textboxes using LINQ2SQL - c#

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

Related

Join List Data from two separate Data Contexts

I have been searching for the solution to this problem and this is what I have so far:
var ProductInfo = (from p in twd.Products
orderby p.PC
where p.DELMARK == active
select p).AsEnumerable();
var BuyersData =
(from x in db.MinimumProductInfo
where x != null
orderby x.ItemCode, x.Region
let pnote =
(from pn in db.ProductNotes
where pn != null
where x.MinimumProductInfoID == pn.MinimumProductInfoID
&& pn.NoteTypeFlag == "p"
orderby pn.NoteDate descending
select pn).FirstOrDefault()
let cnote =
(from c in db.ProductNotes
where c != null
where x.MinimumProductInfoID == c.MinimumProductInfoID
&& c.NoteTypeFlag == "c"
orderby c.NoteDate descending
select c).FirstOrDefault()
let product =
(from p in ProductInfo
where x.ItemCode == p.PC
select p).FirstOrDefault()
select new ProductInfoWithNoteList
{
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
EquivCode = x.EquivCode,
Description = product.PDESC,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Region = x.Region,
Comment = cnote.ItemNote,
PermanentNote = pnote.ItemNote
}).ToArray();
It looks correct but I am getting an error,
'The specified LINQ expression contains references to queries that are
associated with different contexts.'
What this code is supposed to do is pull out all the active product codes from the first table using the twd datacontext then use data from that database in the db.MinimumProductInfo table. The reason they have 2 separate data contexts are they are completely different databases, the first is our ERP and the second is one that we are building in house.
What am I missing? I know it is possible to do this by separating the two datacontexts then adding them together because I have seen it done with single instances but I cannot find how to do it with list data.
Instead of this:
let product =
(from p in ProductInfo
where x.ItemCode == p.PC
select p).FirstOrDefault()
select new ProductInfoWithNoteList
{
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
EquivCode = x.EquivCode,
Description = product.PDESC,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Region = x.Region,
Comment = cnote.ItemNote,
PermanentNote = pnote.ItemNote
}).ToArray();
Try this by removing the let product clause and not filling the properties associated with ProductInfo because we will do that afterwards (See I have commented out the Description property):
select new ProductInfoWithNoteList
{
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
EquivCode = x.EquivCode,
//Description = product.PDESC,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Region = x.Region,
Comment = cnote.ItemNote,
PermanentNote = pnote.ItemNote
}).ToArray();
Now that you have your BuyersData and ProductInfo in memory, set the Description property or all the items in BuyersData:
foreach(var thisBuyerData in BuyersData)
{
var thisPi = ProductInfo.SingleOrDefault(x => x.PC == thisBuyerData.ItemCode);
thisBuyerData.Description = thisPi?.PDESC;
}

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.

associated data in linq select

I need to select data from different tables associated, I have a hospital table, another specialty, and other services, and what is held to select all hospitals and their specialties and services, there is a way to do this in linq?
this is what I'm trying
var hospitalesQuery = from hospital in App.ViewModel.ChristusDB.Hospitales
where hospital.id_tipo == "2" && hospital.christus == "1"
orderby hospital.distancia ascending
from e in App.ViewModel.ChristusDB.EspHosp
where e.fk_hospital==hospital.pk_hospital
from s in App.ViewModel.ChristusDB.ServHosp
where s.fk_hospital==hospital.pk_hospital
select new Hospitale()
{
pk_hospital = hospital.pk_hospital,
nombre = hospital.nombre,
direccion = hospital.direccion,
ciudad = hospital.ciudad,
id_ciudad = hospital.id_ciudad,
estado = hospital.estado,
id_estado = hospital.id_estado,
id_tipo = hospital.id_tipo,
tipo_descripcion = hospital.tipo_descripcion,
imagen = hospital.imagen,
gps_lat = hospital.gps_lat,
gps_lng = hospital.gps_lng,
abierto_lv = hospital.abierto_lv,
abierto_sd = hospital.abierto_sd,
telefono_1 = hospital.telefono_1,
telefono_2 = hospital.telefono_2,
telefono_3 = hospital.telefono_3,
telefono_4 = hospital.telefono_4,
telefono_5 = hospital.telefono_5,
inactivo = hospital.inactivo,
christus = hospital.christus,
especialidades= new List<Especialidade>(e),
servicios= new List<Servicio>(s)
};
You are looking for joining tables by a foreign key. LINQ (asn SQL as well) provide join for this:
from hospital in App.ViewModel.ChristusDB.Hospitales
where hospital.id_tipo == "2" && hospital.christus == "1"
join e in App.ViewModel.ChristusDB.EspHosp on hospital.pk_hospital equals e.fk_hospital
join s in App.ViewModel.ChristusDB.ServHosp on hospital.pk_hospital on s.fk_hospital
orderby hospital.distancia ascending
select new Hospitale()
{...
Update. If you want to load list dependencies for each of the hospitals, I do not think you can do this with one query in EF. This is as close as you can get:
var hospitals = (from hospital in App.ViewModel.ChristusDB.Hospitales
where hospital.id_tipo == "2" && hospital.christus == "1"
orderby hospital.distancia ascending
select new Hospitale()
{
pk_hospital = hospital.pk_hospital,
...
}).ToList();
foreach (var h in hospitals)
{
h.especialidades = App.ViewModel.ChristusDB.EspHosp.Where(e => e.fk_hospital==h.pk_hospital).ToList();
h.servicios = App.ViewModel.ChristusDB.ServHosp.Where(e => s.fk_hospital==h.pk_hospital).ToList();
}
However this would be a lot of queries to the DB, which might perform poorly. You should really think about redesigning your EF data model properly so that the framework does this job of loading dependencies for you.

Can't populate database table

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.

Linq not in select on datatable

Hi i've got 2 data tables (bannedlist,countrylist), both contains list of country names and cods in columns cc and country. I am trying to do a query where i can select countries from countrylist table that are not in bannedlist table in order to create a 3rd table.
Any ideas?
I haven't got too far with this.
var ccList = ds.Tables[2].AsEnumerable();
var bannedCCList = ds.Tables[1].AsEnumerable();
var query = from r in ccList....
..
after trying
var bannedCCList = ds.Tables[1].AsEnumerable();
var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r;
i still get same country list. banned ones haven't been removed. here is more detail in order to explain more. not sure what i am doing wrong
protected void BindCountryBan(string subd)
{
DataSet ds = new DataSet();
ds = new DB().CountryBan_GetSiteSettings();
BannedCountryListBox.DataSource = ds.Tables[1];
BannedCountryListBox.DataValueField = "cc";
BannedCountryListBox.DataTextField = "country";
BannedCountryListBox.DataBind();
//bind country list
var ccList = ds.Tables[2].AsEnumerable();
var bannedCCList = ds.Tables[1].AsEnumerable();
var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r;
//var query = ccList.Except(bannedCCList);
//CountryListBox.DataSource = ds.Tables[2];
DataTable boundTable = query.CopyToDataTable<DataRow>();
CountryListBox.DataSource = boundTable;
CountryListBox.DataValueField = "cc";
CountryListBox.DataTextField = "country";
CountryListBox.DataBind();
}
Except would work if you use it on sequences of the countries:
using System.Linq;
...
var ccList = from c in ds.Tables[2].AsEnumerable()
select c.Field<string>("Country");
var bannedCCList = from c in ds.Tables[1].AsEnumerable()
select c.Field<string>("Country");
var exceptBanned = ccList.Except(bannedCCList);
If you need the full rows where the countries aren't banned, you could try a left outer join:
var ccList = ds.Tables[2].AsEnumerable();
var bannedCCList = ds.Tables[1].AsEnumerable();
var exceptBanned = from c in ccList
join b in bannedCCList
on c.Field<string>("Country") equals b.Field<string>("Country") into j
from x in j.DefaultIfEmpty()
where x == null
select c;
You can use the Except() LINQ extension method like this:
var result = full.Except(banned);
However this will work fine with the default comparer of the contained type. Thus if you want to use a specific column like in your example, you might need another approach like:
from r in ccList
where !bannedCCList.Any(b => b["cc"] == r["cc"])
select r;
Using Except() implies the references are the same in both collections, which I think is not the case with Tables, or correct me if I'm wrong.
Try this:
var query = ccList.Except(bannedCCList);

Categories

Resources