I got this tblDocument table which has a one to many relationship to a couple of other tables. I have created this querystring that displays the content of the document. In this soulution i only display the DocPerson id. What im trying to do is to display the name of the person which is located in the tblPerson table. Can someone help me?
if (!IsPostBack)
{
string strId = Request.QueryString["id"];
int id;
if (int.TryParse(strId, out id))
{
var db = new MyModelContext();
var p = db.tblDocuments.SingleOrDefault(x => x.DocId == id);
if (p != null)
{
lblCaseNr.Text = p.DocNr;
lblPerson.Text = p.DocPerson.ToString();
lblCourt.Text = p.DocCourt.ToString();
lblYear.Text = p.Docyear.ToString();
lblResume.Text = p.DocResume;
lblResult.Text = p.DocResult;
lblLaw.Text = p.DocLaw.ToString();
}
}
}
}
For your LINQ expression, try the following:
var q = from d in db.tblDocuments join p in db.tblPerson
on d.DocId equals p.DocId
where d.DocId == id
select new {d.DocId, p.DocPerson}
If you need to access other fields, simply add them to your select new clause.
Related
I have an error in the binding Of The Telerik RadScheduler I need help. The error is
DataBinding: 'Calender.Model.RadSchedulerData' does not contain a property with the name 'ID'.
I want to know what is the problem? I make alot of search but I do not get the right answer. Please any one know this error please tell me, Thanks.
protected void Page_Load(object sender, EventArgs e)
{
List<RadSchedulerData> lstrsd = new List<RadSchedulerData>();
NewCalenderDBEntities1 Context = new NewCalenderDBEntities1();
int UserID = int.Parse(Request.QueryString["UserID"]);
//int UserID = 1;
Session["UserID"] = UserID;
var Data = (from r in Context.Users
where r.ID == UserID
select new { AppointmentTbl = r.Appointments }).ToList();
var D = (from r in Context.Appointments
where r.RoleId == 1
select new RadSchedulerData { Subject = r.Subject, StartDate = r.Start, EndDate = r.End }).ToList();
lstrsd.AddRange(D);
foreach (var item in Data)
{
foreach (var i in item.AppointmentTbl)
{
var DD = Context.Appointments.Where(w => w.RoleId == 2 && w.ID == i.ID).Select(s => new RadSchedulerData
{
Subject = s.Subject,
StartDate = s.Start,
EndDate = s.End
}).ToList();
lstrsd.AddRange(DD);
var AllSharedData = Context.Appointments.Where(w => w.RoleId == 3 && w.ID == i.ID).Select(s => new RadSchedulerData
{
Subject = s.Subject,
StartDate = s.Start,
EndDate = s.End
}).ToList();
lstrsd.AddRange(AllSharedData);
}
}
RadScheduler1.EnableCustomAttributeEditing = true;
RadScheduler1.DataKeyField = "ID";
RadScheduler1.DataSource = lstrsd;
RadScheduler1.DataBind();
}
If you read the error message carefully again, you will probably see the problem by yourself:
DataBinding: 'Calender.Model.RadSchedulerData' does not contain a property with the name 'ID'.
It simply means that the control is trying to fetch a value for the property ID on the RadSchedulerData class and it cannot find it. This could mean, it doesn't exist or that it is not public.
The reason the control is trying to read that specific property on that class is because in the code sample, the DataSource property of the RadScheduler is set to a List<RadSchedulerData> and its DataKeyField property to ID.
To fix the binding error, you either
create (and populate) an ID property in the RadSchedulerData class
make the ID property public in the RadSchedulerData class
give the RadScheduler.DataKeyField a different property name that exists in RadSchedulerData
change the RadScheduler.DataSource property to a list of other object types that have an ID property .
I have a form with 2 dropdown lists and 3 checkbox sections that users select from to search the database. Since all of the tables are small, I'd like to use a single SELECT statement to return the results. I found an extension on mikesdotnetting that works great with a single IN clause
using System;
using System.Collections.Generic;
using WebMatrix.Data;
using System.Linq;
public static class DatabaseExtensions
{
public static IEnumerable<dynamic> QueryIn(this Database db, string commandText, string values)
{
if (string.IsNullOrEmpty(values))
throw new ArgumentException("Value cannot be null or an empty string", "values");
var temp = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var temp2 = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var temp3 = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var parms = temp.Select((s, i) => "#" + i.ToString()).ToArray();
var parms2 = temp2.Select((s, i) => "#" + i.ToString()).ToArray();
var parms3 = temp3.Select((s, i) => "#" + i.ToString()).ToArray();
var inclause = string.Join(",", parms, parms2, parms3);
return db.Query(string.Format(commandText, inclause), temp, temp2, temp3);
}
public static int ExecuteIn(this Database db, string commandText, string values)
{
if (string.IsNullOrEmpty(values))
throw new ArgumentException("Value cannot be null or an empty string", "values");
var temp = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var parms = temp.Select((s, i) => "#" + i.ToString()).ToArray();
var inclause = string.Join(",", parms);
return db.Execute(string.Format(commandText, inclause), temp);
}
}
Here is the page code showing how I envision the query:
var gender = Request["genderSvd"];
var person = Request["chkPerson"];
var spec = Request["chkSpec"];
var county = Request["ctyLoc"];
var crim = Request["chkCrim"];
var db = Database.Open("HBDatabase");
var sql = "SELECT DISTINCT tblProgram.* FROM lnkPrgPersonSvd INNER JOIN tblProgram ON lnkPrgPersonSvd.prgId = tblProgram.prgId";
sql += "INNER JOIN lnkPrgSpecial ON tblProgram.prgId = lnkPrgSpecial.prgId INNER JOIN tblProgram.prgId = lnkPrgCriminal.prgId ";
sql += "WHERE (lnkPrgPersonSvd.personId IN ({0})) AND (lnkPrgSpecial.specId IN ({1})) AND tblProgram.prgGenderSvdId = #2 ";
sql += "AND tblProgram.prgCounty = #3 AND (lnkPrgCriminal.criminalId IN ({4}))";
var prgList = db.QueryIn(sql, person, spec, gender, county, crim);
That, obviously, doesn't work, because the extension cannot take that many arguments. I'm looking for a way to modify the class to allow for the additional parameters so that the query can run with just the one execution. This may not be possible.
Also, I did find several threads that dealt with handling a single parameterized in clause, but no real mention of multiples with variable lists.
I am not adept with stored procedures or writing my own classes. Any suggestions?
Am new to DNN Module development and using MVC and Linq. Have built a class and controller that allows me to create a record in a table on the database. Can anyone tell me the best way to retrieve the id of the newly created record? The part of the controller for creating the record is below.
class BlockController
{
public void CreateBlock(Block b)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Block>();
rep.Insert(b);
}
}
}
Call to the controller from the code
var bC = new BlockController();
var b = new Block()
{
SectionId = int.Parse(ddlPickSection.SelectedValue),
PlanId = int.Parse(ddlPickPlan.SelectedValue),
BlockName = bId,
BlockDesc = "",
xPos = bX,
yPos = bY,
width = arrBWidths[i],
ModuleId = ModuleId,
CreatedOnDate = DateTime.Now,
CreatedByUserId = UserId,
LastModifiedOnDate = DateTime.Now,
LastModifiedByUserId = UserId,
};
bC.CreateBlock(b);
Thanks
When you submit changes (insert the record in DB) the ID would available in b object:
...
rep.InsertOnSubmit(b);
ctx.SubmitChanges();
int desireID = b.id;
I have two tables: ServiceType and ServiceTerm.
The tables go hand in hand with one another, and get combined into the associative table ServiceRate. One ServiceType can have multiple ServiceTerms, but not always all of them.
On my asp.net form (VB) I want to code it to where there's a way for me to add each line to the database using a checkbox to select the ServiceTerms that apply to the selected ServiceType.
I'm completely new to asp.net, and pretty new to SQL Server 2008, too.
Here is an example I have done in one of my projects :
where chSportsList is Id for checkbox list
List<ListItem> list_chSportsList = new List<ListItem>();
foreach (ListItem chsli in chSportsList.Items)
{
Guid gui2 = Guid.Parse("00000000-0000-0000-0000-000000000000");
try
{
gui2 = Guid.Parse(chsli.Value.ToString());
}
catch { Response.Redirect("default.aspx"); }
db = new IRANSportEntities();
Customer_Sports customer_Sport = new Customer_Sports();
customer_Sport = db.Customer_Sports.FirstOrDefault(x => x.Id_Customer == gui1 && x.Id_Sports == gui2);
if (customer_Sport == null)
{
if (chsli.Selected == true)
{
db = new IRANSportEntities();
Customer_Sports _save = new Customer_Sports() { Id = Guid.NewGuid(), Id_Customer = gui1, Id_Sports = gui2 };
db.Customer_Sports.AddObject(_save);
db.SaveChanges();
}
}
else
{
if (chsli.Selected == false)
{
db.Customer_Sports.DeleteObject(customer_Sport);
db.SaveChanges();
}
}
}
This is the update code I found:
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
//Change the Employee Name in memory
e.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}
Now what I am doing is like this:
using(CRNNSTestEntities crnnsupContext = new CRNNSTestEntities())
{
CPersonalInfo t = ((IQueryable<CPersonalInfo>)Cache["personquery"]).First();
t.Tombstone.Address = Address1.Text;
System.Windows.Forms.MessageBox.Show(crnnsupContext.SaveChanges()+"");
};
which doesn't work. So my question is do I have to write something like CPersonalInfo t = from t in ....
Why doesn't my method doesn't work?
Thanks
You need to get the entity CPersonalInfo t from your crnnsupContext and not from your Cache
You can also attach object to the context before.
More info how to use attach here
can you change this
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
//Change the Employee Name in memory
e.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}
into
using (TestDBEntities ctx = new TestDBEntities())
{
//Get the specific employee from Database
Emp e = (from e1 in ctx.Emp
where e1.Name == "Test Employee"
select e1).First();
var entity = ctx.Emp.Find(e);
//Change the Employee Name in memory
entity.Name = "Changed Name";
//Save to database
ctx.SaveChanges();
}