update linq to sql values with select new keyword - c#

How to update linq to sql values with select new keyword with anonymous types because I am using var keyword with select new query I need in in this but it returns an error like this
Compiler Error Message: CS0200: Property or indexer 'AnonymousType#1.Code' cannot be assigned to -- it is read only
This is my code:
var ProjectView12 = (from x in db.Projects
select new
{
add = db.Locations.Where(y = > y.ID == x.RegionID).FirstOrDefault().Name,
Province = db.Locations.Where(y = > y.ID == x.ProvinceID).FirstOrDefault().Name,
District = db.Locations.Where(y = > y.ID == x.DistrictID).FirstOrDefault().Name,
Code = x.Code,
Name = x.Name,
ProjectIdentificationDate = db.Milestones.Where(y = > y.ProjectID == x.ID && y.StageID == 1 && y.ComponentID == 1 && y.ModuleID == 1).FirstOrDefault().Date.ToString(),
ProjectLat = Convert.ToDecimal(x.Lat),
ProjectLong = Convert.ToDecimal(x.Lon),
Remarks = db.Milestones.Where(y = > y.ProjectID == x.ID && y.StageID == 1 && y.ComponentID == 1 && y.ModuleID == 1).FirstOrDefault().Remarks.ToString(),
}).ToList();
foreach(var item in ProjectView12)
{
item.Code = txtSubProjectCode.Text;
item.Name = txtSubProjectName.Text;
item.ProjectLat = Convert.ToDecimal(txtLatitude.Text);
item.ProjectLong = Convert.ToDecimal(txtLongitude.Text);
item.ProjectIdentificationDate = txtDate.Text;
item.Remarks = txtRemarks.Text;
} // txtLocation.Text = item.Region + ">" + item.Province + ">" + item.District;
try
{
db.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}

Well, you're getting the compiler error because - as it says - the properties of anonymous types are read-only in C#.
More fundamentally, even if you could modify them, you'd have to expect LINQ to SQL to reverse whatever you put into your projection in order to update the original tables. That seems a fairly tall order to me - particularly for the Remarks property in this particular case.
Basically, in order to update the database, you need to make changes to the entities that are mapped from your tables. Make your query select the relevant entities, then you can project from those later on in client-side code, if necessary - so long as you've still got a reference to the entity to modify.

Related

Building where statement dyamically

I have a list where I wish to add items to dyanmically in the where clause if I dont have a user id at present the linq will fall over.
List<ScreenermissionsForSearch> _screen = new List<ScreenermissionsForSearch>();
_screen= _security.GetScreenermissionsForSearch();
gridControl1.DataSource = _screen.Where(w => w.Code ==
Convert.ToInt32(txtUserId.Text) || w.ScreenName ==dbscreenanme.Text).ToList();
this.gridView1.Columns[0].Width = 50;
this.gridView1.Columns[1].Width = 100;
So I need some wway of being able to append to the where clause checking if the string is null or not first or am I not doing this right in the frist place?.
Edit to show clairty Here it is just listing them all when i want it to only show provider if user id is empty.
It works here and shows fine as should do but its not for the other condition
New Code
_screen= _security.GetScreenermissionsForSearch();
gridControl1.DataSource = _screen.Where(w => string.IsNullOrEmpty(txtUserId.Text) || w.ScreenName == dbscreenanme.Text).ToList();
this.gridView1.Columns[0].Width = 50;
this.gridView1.Columns[1].Width = 100;
Add this condition to where clause string.IsNullOrEmpty(txtUserId.Text) and change the condition;
gridControl1.DataSource = _screen.Where(w =>
(string.IsNullOrEmpty(txtUserId.Text) || w.Code == Convert.ToInt32(txtUserId.Text)) &&
w.ScreenName == dbscreenanme.Text)).ToList();
If you don't want to get result when parsing is failed try following code;
gridControl1.DataSource = _screen.Where(w =>
w.Code == int.TryParse(txtUserId.Text,out var val) ? val : -1 &&
w.ScreenName == dbscreenanme.Text)).ToList();
var entity = Context.Parents.Include(x => x.Name).ToList();

Using Checkbox to join indexes for search in c# for mysql

I have made a simple database search program using c# linq and mysql(code below) which works pretty well. This database has 16 columns 6 of which are for address (State,City,District,Street, Building Name, Door Number). My code now searches for many variations of indexes aside from anything related to address and as seen below ID is overriding value. What my prof. wants is to search with ID and address values to find who might be from the same place. The way this is wanted is to have a checkbox.
If checkbox is clicked and ID entered the search result returned with everyone with the same address and if nobody else has the same address then just the entered ID value to return.The rest of the index values doesn't needed for this operation. My problem with this whole equation is I can't find any applicable way to join the 6 address columns and do a double search with ID and the whole adress. I have to use linq as it is required.
Code Sample;
var query = from i in sqlcmd.table select i;
if (ID.Text.Length > 0)
{
double id = Convert.ToDouble(ID.Text);
query = query.Where(s => s.ID == id);
}
else
{
if (Name.Text.Length > 0)
{
query = query.Where(s => s.Name == Name.Text);
}
if (Sname.Text.Length > 0)
{
query = query.Where(s => s.Sname == Sname.Text);
}
if (ClassList.Text.Length > 0)
{
query = query.Where(s => s.ClassList == ClassList.Text);
}
}
gridview.DataSource = query.ToList();
P.S: Thx to #juancarlosoropeza for heads-up of the mess of a question I made.
just include the check value on the if conditions.
if (chkName.Checked && Name.Text.Length > 0)
{
query = query.Where(s => s.Name == Name.Text);
}
if (chkSName.Checked && Sname.Text.Length > 0)
{
query = query.Where(s => s.Sname == Sname.Text);
}
if (chkClassList.Checked && ClassList.Text.Length > 0)
{
query = query.Where(s => s.ClassList == ClassList.Text);
}
I don't know if I completely understood what you are looking for but I'll give it a try.
If I got you right you are looking for a way to find anybody who has the same address as the person with a given ID. If you want to exclude the person with the given ID just uncomment the last line in the where-clause of the query.
var query = from i in sqlcmd.Table select i;
if (ID.Text.Length > 0)
{
var personGivenByID = from person in query.AsEnumerable()
where person.ID == Convert.ToDouble(ID.Text)
select person;
var sameAddressLikeGivenPerson = from row in query.AsEnumerable()
where row.State == personGivenByID.FirstOrDefault().State
&& row.City == personGivenByID.FirstOrDefault().City
&& row.District == personGivenByID.FirstOrDefault().District
&& row.Street == personGivenByID.FirstOrDefault().Street
&& row.BuildingName == personGivenByID.FirstOrDefault().BuildingName
&& row.DoorNumber == personGivenByID.FirstOrDefault().DoorNumber
//&& row.ID != personGivenByID.FirstOrDefault().ID
select row;
gridview.DataSource = sameAddressLikeGivenPerson != null ? sameAddressLikeGivenPerson : sameAddressLikeGivenPerson;
}

I cant seen to use ToList(); or take(6) items on this select statement

I cant seen to use ToList(); or take(6) items on this select statement.
I need to select only 6. this is what i have witch works but displays 1 only on the 6 iterations of the repeater.
public string GetImage(string pId)
{
Compras context = new Compras();
Product pr = context.Products.FirstOrDefault();
if (pr != null && pr.Picture != null && pr.Picture.Count() > 0)
{
return "data:image/jpg;base64," + Convert.ToBase64String((pr.Picture));
}
return "data:image/jpg;base64," + Convert.ToBase64String(File.ReadAllBytes(Server.MapPath("~/") + "white.jpg"));
}
I wish i could use as on this next:
var context = new Compras();
var prouctQ = from p in context.Products.Take(6) select new { p.ProductName, p.Picture }; //with projections
var Products = prouctQ.ToList();
if (Products.Count > 0)
Please make sure that you have "using System.Linq" at the top of the code file.

Search keyword using linq in asp.net with c#back end

List<search> alllist = wsWSemloyee.GetAllProject(); //where search is model class contains properties..
string search_key = "%" + txtsearch.Text.Trim() + "%";
List<search> result = new List<search>();
foreach (search item in alllist)
{
var op = (
from a in alllist
where a.Sfirstname.Contains(search_key) || a.Slastname.Contains(search_key) || a.Smob.Contains(search_key) || a.Scity.Contains(search_key) || a.Sstate.Contains(search_key)
//where SqlMethods.Like(a.Sfirstname,search_key)||SqlMethods.Like(a.Slastname,search_key)||SqlMethods.Like(a.Scity,search_key)||SqlMethods.Like(a.Smob,search_key)||SqlMethods.Like(a.Sstate,search_key)
select a
);
// List<search> lst = op.ToList<search>();
if (op != null)
{
result.Add(item);
}
}
if (result.Count != 0)
{
dgv_searchreport.DataSource = result;
dgv_searchreport.DataBind();// data grid view
}
its not working...
giving all result present in alllist..
//where search is model class contains properties..
I'ts because you are comparing if result of your linq query is not null and then adding variable from foreach clause. When any single item from allproducts will match condition then op will be never null and then whole collection will be contained in result. What you want is probably following:
var result = (from a in alllist
where a.Sfirstname.Contains(search_key)
|| a.Slastname.Contains(search_key)
|| a.Smob.Contains(search_key)
|| a.Scity.Contains(search_key)
|| a.Sstate.Contains(search_key)
select a).ToList();
That will pick all items which match condition and enumerate them to list.
May this helps you..
string search_key = txtsearch.Text.Trim(); // instead "%" + txtsearch.Text.Trim() + "%";
List<search> result = new List<search>();
var op = (from a in alllist
where a.Sfirstname.Contains(search_key) || a.Slastname.Contains(search_key) || ......
select a);
if(op.Count() > 0)
result = op.ToList();

EF Duplicated Value

Im getting angry with this error and cannot solve it.
Please, some Jedi master help me.
I'm trying to save trhee Entities: Region, Content and RegionalContent. Region is OK but Regional Content has to be associated with one Content and each Content may have Many RegionalContents(Translations). But I always get a DbUpdateException that has a UpdateException that has a SqlCeException that says something like:
*Impossible to insert a duplicated value with same index. Table name = XBLContents,Constraint name = PK_XBLContents_000000000000001C *
I'm debugging it for some days and could not find the error. Please, note that I'm still a little Padawan.
This is the code that saves the objects in they proper Tables:
Region region;
if (!db.Regions.Any(x => x.ID == Locale))
{
region = new Region { ID = Locale };
db.Regions.Add(region);
db.SaveChanges();
}
else
region = db.Regions.SingleOrDefault(x => x.ID == Locale);
for (int i = start; i < (start + 2); i++)
{
string guid = itens[i].Groups["guid"].Value;
Content c = new Content(guid);
if (!db.Contents.Any(x => x.GUID == guid))
{
c.Type = Type.ToString();
c.PopularInfo(Locale);
db.Contents.Add(c);
}
else
c = db.Contents.SingleOrDefault(x => x.GUID == c.GUID);
RegionalContent regionalcontent;
if (!db.RegionalInfos.Any(x => x.ContentId == guid && x.RegionId == Locale))
{
if (c.HTML == null)
c.PopularInfo(Locale);
regionalcontent = new RegionalContent(c, Locale);
regionalcontent.Region = region;
regionalcontent.Name = HttpUtility.HtmlDecode(itens[i].Groups["name"].Value);
db.RegionalInfos.Add(regionalcontent);
db.Contents.Add(c);
db.SaveChanges();
}
else
regionalcontent = db.RegionalInfos.SingleOrDefault(x => x.ContentId == guid && x.RegionId == Locale);
c.RegionalInfo.Clear();
regionalcontent.Region = region;
c.RegionalInfo.Add(regionalcontent);
Contents.Add(c);
}
You are calling SingleOrDefault when you know 1 already exists. Just use Single.
I would not call SaveChanges to the very end.
Are you sure the GUIDs are unique every time?

Categories