I had a complex view joining a couple of tables but it freezed my C# app so I simplified it in order to get it to work, however it still freezes and I dont have a clue why.
I have a table called 'admittances' containing: AdmittanceID, Number, Date, Notes.
I created a view which selects three of those: AdmittanceID as ID, Number as Number and Date as Date.
In a database it just works, no big deal. I mapped it via 'Update model from database' option in a model wizard inside C# EF model and it shows up as an entity with three columns and entity key column 'ID'.
However while trying to loop over all the records the program stops working and does not go any further (in debugging it just does not pass through the loop).
meraserwEntities db = new meraserwEntities();
var myQuery = db.clientstodevices.ToList();
//Tried also other versions that are listed below
var myQuery = from d in db.clientstodevices select d;
foreach (var item in myQuery)
{
ClientsToDevices.Add(item);
}
// Or without loop - then it freezed exactly in this line
ClientsToDevices = db.clientstodevices.ToList();
Please help, tried everything ..
Related
In this system one program creates table records and a second updates them. I want the update program to see the new records. See lots of queries/responses to this but so far none have worked for me. One solution was to clear and reload the dataset table. The following code recreates the dataset but I can't include the auto incremented primary key bookid. If it is there I get an overload error even thought the field count is correct. If I remove it the dataset.booking table is loaded but the bookid values are wrong negative numbers) and I can't update the dataset.booking table as it does not match the database table.
tclDataSet3.booking.AcceptChanges();
tclDataSet3.booking.Clear();
bookingBindingSource.ResetBindings(false);
dataGridView1.ClearSelection();
var bkas1 = tcdb.bookings.Where(b => b.approvalStatus == 1);
foreach (booking bk in bkas1)
tclDataSet3.booking.AddbookingRow(
(int)bk.bookId,
(int)bk.bookYear,
(int)bk.bookMonth,
(int)bk.bookDay,
(int)bk.workOrder,
(int)bk.customerNum,
bk.firstName,
bk.lastName,
bk.vehicle,
(int)bk.serviceCar,
bk.repairType,
(bool)bk.isCompleted,
(bool)bk.isPickedUp,
bk.outYear,
bk.outMonth,
bk.outDay,
(bool)bk.isDeleted,
(int)bk.isUpdated,
bk.bookingTime,
(int)bk.approvalStatus);
Program requirements:
display datagridview of dataset.booking table where as_code = 1
updates rows in datagrideview to change as_code = 2
remove updated rows from datagridview (bookingBindingSource.RemoveCurrent(); works well)
Refresh datagridview to see all dataset.booking table rows where as_code = 1
Currently the refresh only sees existing records in the datagrideview.
Is there a better way to do this?
After much trial and error I decided to rewrite the code to manually build the dataGridView rather than use any data binding. I created a subroutine to clear the dataGridView, read the base table and rebuild the dataGridView.
I started working on a project in my work that doesn't have any documentation, and the person who developed the project in the first place isn't avalaible anymore.
There is this piece of code for doing and update to the database
_report = db.Report.Where(x => x.IdReport == ReportId).FirstOrDefault();
db.Report.Attach(_report);
_report.attr1 = reportmodel.attr1;
_report.attr2 = reportmodel.attr2;
_report.attr3 = reportmodel.attr3;
if (db.SaveChanges() != 0)
{
return View(reportmodel)
}
Looks fine and indeed does the update to the database in the table "Report", but additionally it is being inserted in another table "ReportLog" the detail of the change (orginal value, new value), I believe this is being done somehow in the SaveChanges().
So my question is where can I find where those insertions to the log table are being executed?
I have checked in the model if the table "Report" has some stored procedure mapped in the update action, checked for triggers and stored procedures in the database and used Find(Ctrl+f) to check for "ReportLog" in the entire solution, but I couldn't find where the insertion is being executed.
And something really weird is that this happens for the "Report" table only, using SaveChanges() for other updates in other tables does only what is expected
I found a trigger on the Report table that was doing the inserts
I am using EF6 to query data from a database. The database existed before the code and belongs to another application, so I cannot modify the database at all. I believe I am using a code first approach, even though the database already exists(Forgive me as I'm new to EF). The issue is that I am not able to pull back data for a column that is setup as follows;
[Column("ITEM_QTY")]
public decimal ItemQuantity { get; set; }
Now if I rename the property to ITEM_QTY, it pulls the data correctly. I'm not sure what I'm missing. I can pull data from any other field correctly, but this field returns 0 regardless of whats in the DB. Can anyone provide any direction?
In another discussion, someone had suggested a possible issue with the underscores in the column name. Not sure if that could be it, but adding for info. Thanks.
Edit: Adding code used to query database. Note that this was setup before I started working on the project, so following same convention;
var t = this.Database.SqlQuery<InventoryDb>("select top 100 * from COMPANY_INVENTORY with (NOLOCK) where COMPANY = #CompanyName",
new SqlParameter("CompanyName", companyName)).ToList();
Your Column attribute will be ignored if you are using custom SqlQuery<T> on the DbContext. You need to pass the Sql statement with the alias for the property name that matches your entity.
var t = this.Database.SqlQuery<InventoryDb>("select top 100 Item_QTY as [ItemQuantity], ... other columns ... from COMPANY_INVENTORY with (NOLOCK) where COMPANY = #CompanyName",
new SqlParameter("CompanyName", companyName)).ToList();
EDIT:
Was checking this further out of curiosity and it appears that EF should respect the Column attribute if you used the DbSet.SqlQuery instead. I have not tried this though. (https://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=vs.113).aspx)
var t = this.Inventory.SqlQuery("select top 100 * from COMPANY_INVENTORY with (NOLOCK) where COMPANY = #CompanyName",
new SqlParameter("CompanyName", companyName)).ToList();
I recently upgraded a project from VS2012 to VS2013 (it was originally created in 2010) and also upgraded the reference to one of the database providers (Pervasive.Data.Common, Pervasive.Data.SqlClient, Pervasive.Data.SqlClient.Entity) to the newer 4.0 version. On doing this, two lines of code that were previously working no longer properly refresh the data in their queries, which are inside a using statement that is inside a function that is called each time, so there should be no long-lived objects, including both contexts and entity objects (all other statements work properly.) The code lines at issue attempt to pull a single purchase order header tuple from the po table and a single purchase order detail line item tuple from the po_dtl table. Placing a context.refresh call at the beginning of the code inside the using statement causes the data to properly refresh, but is a serious performance killer and won't work for production, not to mention that there should be no need to refresh, EF should be running the query anew each time the function is called.
Below is a portion of the code with the meat of the function left out for clarity. I have also left out the po_dtl portion of the code, as the queries to determine which po_dtl tuple to use are complex and would make the code hard to read. The line of code that is failing is noted by a comment saying so.
I have stepped through the code multiple times and have verified that
the context object always APPEARS to be brand new at the beginning of the statement, having no tracked entities
the value of poNum (the id of the po header being looked up) changes as expected
no matter what value poNum has, the po header that was returned by the very first execution of the query is always returned by this line of code
public ReceivePieceInfo(AdvanceShippingNoticePiece item, int profitUserId, Inventory.Location receiveLocation, DateTime receiveDate, string tripNumber)
{
// LinqContextMaster.NewProfitContext provides a brand new
// context each time it is called
using (Profit.ProfitDatabase pd = LinqContextMaster.NewProfitContext)
{
decimal poNum = decimal.Parse(item.PurchaseOrderNumber);
decimal poLineNum = decimal.Parse(item.PurchaseOrderLineNumber);
IEnumerable<Profit.po> profit_pos = null;
// THIS IS THE BROKEN CODE - no matter what poNum is, this
// query always returns the very first PO that was queried
profit_pos = pd.po.Where(po => po.po_no == poNum);
Profit.po profit_po = null;
if (profit_pos.Count() == 1)
profit_po = profit_pos.Single();
}
}
I've got a SQL Server database that I'm trying to build a RESTful API for.
I'm using ADO.Net and Linq to retrieve a single row from a table like this:
[HttpGet]
public tTrip getTripById(Guid id)
{
var _trip = (from trips in db.tTrip
where trips.ID == id
select trips).FirstOrDefault();
return _trip;
}
When I debug the code the correct object is retrieved. If I keep running however, there will be no response. I'm guessing that's because for every foreign key present in the returned row, ADO does another lookup through the other mapped tables which slows down everything by a lot.
If I only select a single column that doesn't contain any FKCs everything works fine.
Any ideas how I can turn off the FKC lookup for that fetched object?
Thank you!
I found the problem - In the ObjectContext class (that's where the 'db' variable comes from btw), I had the ContextOptions.LazyLoadingEnabled variable set to true.
Set it to false and the application returns only the Guid for every entry instead of loading the entry details from the database.