I have a ObservableCollection<Admissiontb> and i want to add this list to Sql Table.
The following code only add last record! Seeking any help and thanks in advance.
private void AddrecordToSql(object obj)
{
AdmissiondbEntities db = new AdmissiondbEntities();
foreach (var item in admissiontbsColl)
{
db.Admissiontbs.Add(item);
}
db.SaveChanges();
MessageBox.Show("Done");
}
Trying to add records from the collection to the SQL table
You could try using addrange instead.
You need to call .ToList() on your observablecollection which is in the system.linq namespace ( using ).
Then you can do something like is explained here:
https://www.tektutorialshub.com/entity-framework-core/add-record-add-multiple-records-in-entity-framework/
AdmissiondbEntities db = new AdmissiondbEntities();
var addList = admissiontbsColl.ToList();
db.Admissiontbs.AddRange(addList);
db.SaveChanges();
MessageBox.Show("Done");
Related
I'm writing a linq-to-sql query to delete a list of records: I pass in a list of RecordID and I want the corresponding records deleted.
This is what I have so far:
public void DeleteMyRecords(List<long> TheRecordIDs)
{
using (TheDC MyDC = new TheDC()) //TheDC is the DataContext
{
MyDC.DeleteOnSubmit(from a in MyDC.TheTable
where TheRecordIDs.Contains(a.RecordID)
select a).SubmitChanges();
}
}
For now, I see the DeleteOnSubmit underlined in red. How do you write such query so that it works?
Thanks for your help.
As query may return more then one record you may need to call DeleteAllOnSubmit
var records = from a in MyDC.TheTable
where TheRecordIDs.Contains(a.RecordID)
select a;
MyDC.TheTables.DeleteAllOnSubmit(records);
MyDc.SubmitChanges();
I am currently trying to create a new order (which will be shown below) in a web service, and then send that data to insert a new row into the database. For some reason my DBML / Data Context does not allow me to use InsertOnSubmit.
Any ideas? I haven't used Linq to Sql in about 7 months.
Thanks in advance.
[WebMethod]
public string InsertOrderToDatabases()
{
//Start Data Contexts ------
DataContext db = new DataContext(System.Configuration.ConfigurationManager.AppSettings["RainbowCMSConnectionString"]);
DataContext dcSqlOES = new DataContext(System.Configuration.ConfigurationManager.AppSettings["OESConnectionString"]);
//Get table from local database
Table<Schedule> Schedule = db.GetTable<Schedule>();
//Find last order number in databases
var lastOrderNumber = from lOrder in Schedule
orderby lOrder.templ_idn descending
select lOrder.templ_idn;
int firstOrderID;
var firstOrder = lastOrderNumber.FirstOrDefault();
firstOrderID = firstOrder.Value + 1;
qrOrder qrOrd = new qrOrder
{
.... data in here creating a new order
};
//TODO: fix below with an insert on submit
if (qrOrd != null)
{
// **Schedule.InsertOnSubmit(qrOrd);**
}
//db.GetTable<Schedule>().InsertOnSubmit(qrOrd);
try
{
//Submit the changes to the database
db.SubmitChanges();
return "Orders were sent to the databases.";
}
catch ()
{
}
}
Based on your response, it appears that you are using the wrong table, or perhaps the wrong data type. I also noticed that when you declare your localSchedule variable, you declare it as type Table<Schedule>, which means it should contain Schedule entities, not qrOrder entities.
Table<TEntity>.InsertOnSubmit expects a specific strongly typed entity to be passed in. In your case, it is expecting Web_Service.Schedul‌e, but you are trying to pass in a qrOrder.
Schedule.InsertOnSubmit(qrOrd);
That line will not treat to submit changes to connected entity , Try this
db.Schedule.InsertOnSubmit(qrOrd);
db.SubmitChanges();
you can try with
db.GetTable(typeof(Schedule)).InsertOnSubmit(qrOrd);
Or
db.GetTable(qrOrd.GetType()).InsertOnSubmit(qrOrd);
I have a table that has 2 columns: FruitID, FruitSize. I want to write a query that takes in a list of FruitIDs and a FruitSize and that sets the new FruitSize for all the fruits.
This is what I have so far:
public void ChangeFruitSizes(List<long> TheFruitIDs, long NewFruitSize)
{
using (SomeDC MyDC = new SomeDC())
{
var TheFruits = (from f in MyDC.Fruits
where TheFruitIDs.Contains(f.FruitID)
select f).ToList();
foreach (Fruits f in TheFruits)
{
f.FruitSize = NewFruitSize;
}
MyDC.SubmitChanges();
}
}
It's currently not bugging but the fields in the database aren't updated. Thanks for your suggestions.
To write this in more concise way, you can try ForEach() in list like below:
using (SomeDC MyDC = new SomeDC())
{
(from f in MyDC.Fruits
where TheFruitIDs.Contains(f.FruitID)
select f).ToList().ForEach(F => F.FruitSize = NewFruitSize);
MyDC.SubmitChanges();
}
Just looking at the code everything is correct. Probably the error is at what is not shown: The model. I suspect you don't have a primary key defined. Define a primary key on the ID field and re-create the model (remove the table from the designer and add it back).
Hello everone
I have a function
public void RemoveStock(string tickerName) {
int key = this.getKeyFromtickerName(tickerName);
foreach (var item in listingDataTable.Where(
x => x.stock == key).ToList()) {
listingDataTable.RemoveListingRow(item);
}
listingTa.Update(listingDataTable);
}
Definitions:
listingDataTable = new stockDataSet.ListingDataTable();
listingTa = new stockDataSetTableAdapters.ListingTableAdapter();
Database type: SQL Server Compact Edition
The function remove rows from the dataset, but not from the database. All additions to the database is stored but I can't delete from the database.
Do I need to do something else to make the database to accept my changes?
Best Regards
Gorgen
Try this instead:
foreach (var item in listingDataTable.Where(
x => x.stock == key).ToList()) {
item.Delete();
}
I think this will actually mark the row for deletion.
Turned out that I needed to add an DeleteCommand in my database adapter. The DeleteCommand wasn't automaticly generated and when using .RemoveListingRow(item) no error message was issued, it just didn't work.
In Data Sources choose "Edit DataSet with Designer" Properties of tableAdaper generate command such as
DELETE FROM Listing
WHERE (stock = #p1)
[OperationContract]
public List<AlumniRegDetails> GetRecord()
{
using (Entities context = new Entities())
{
return (from c in context.Alumni_Registration
select new AlumniRegDetails
{
RegNo=c.RegNo,
Name=c.Name,
Gender=c.Gender,
Ay_Yr= c.AY_ID,
CellNo= c.CellNo,
BranchId=c.BranchId,
EmailId=c.EmailId,
facebookId=c.FacebookId,
LinkedID=c.LiknedInId,
googlePlusID=c.GooglePlusId,
Address=c.Address,
CountryId=c.CountryId,
StateId=c.StateId,
City=c.CityId,
Designation=c.DesginationId,
Occupation=c.OccupationId,
}).Take<AlumniRegDetails>(50).ToList<AlumniRegDetails>();
}
}
i have this code written in Service.svc.cs file in Silverlight.
This code of line---Take(50).ToList();let me retrieve 50 records from Database.
My requirement is it should retrieve all the records from the database without any limitations.
Can anyone correct me?
Remove the Take and it will return all the records. Keep the ToList() if you need a List<T>.
}).Take(50).ToList();
==>
}).ToList();
Replace
}).Take<AlumniRegDetails>(50).ToList<AlumniRegDetails>();
with
}).ToList<AlumniRegDetails>();