EF CF Linq-to-Sql, save an attached child entity? (.NET 4) - linq

I got this code to update only the specific fields of an object.
var myEntity = new DBEntity { Id = 1, Field1 = true, Field2 = "Test" };
context.DBEntities.Attach(myEntity);
var entry = context.Entry(myEntity);
entry.Property(x => x.Field1).IsModified = true;
entry.Property(x => x.Field2).IsModified = true;
context.SaveChanges();
This work perfectly. Now i want to add a log entry to my entity object, each time someone makes an update i want to track it in my logs.
var myEntity = new DBEntity { Id = 1, Field1 = true, Field2 = "Test" };
var logEntry = new DBEntityLog { LogText = "Update to field1 and field2" };
myEntity.Logs.Add(logEntry);
context.DBEntities.Attach(myEntity);
var entry = context.Entry(myEntity);
entry.Property(x => x.Field1).IsModified = true;
entry.Property(x => x.Field2).IsModified = true;
// Property does not work on collection objects
context.SaveChanges();
Now how can i save the logEntry to the database as well? Right now it will still only update the fields.

Problem solved by fetching the log entry and set the EntityState to added.
var entryLog = cibtext,Entry(logEntry);
entryLog.State = EntityState.Added;

Related

Bind List to GridviewComboboxcolumn in telerik radgrindview (winform)

I have a generic List like
List<return> returnlist
class return
{
public string returnid {get; set;
...
public List<string> Vouchernumbers
}
I bind the returnlist to the telerik radgridview.
How can i bind the voucherlist to the GridviewComboboxcolumn for each row ?
I have bind the voucherlist to the combobox after radgridview_complete_binding.
You need to create the grid with columns and data
You need to add the combobox column, initialize it.. Please check you need to have a dataeditor in here
Assign the string to datasource
comboColumn.DataSource = new String[] { "Test1", "Test2"};
You can bind the collections too:
Binding list BindingList<ComboBoxDataSourceObject> list = new BindingList<ComboBoxDataSourceObject>();
ComboBoxDataSourceObject object1 = new ComboBoxDataSourceObject();
object1.Id = 1;
object1.MyString = "Test 1";
list.Add(object1);
ComboBoxDataSourceObject object2 = new ComboBoxDataSourceObject();
object2.Id = 2;
object2.MyString = "Test 2";
list.Add(object2);
colboCol2.DataSource = list;
radGridView1.Columns.Add(colboCol2);
create radcombobox and set datasource and add it to rad grid
eg :
GridViewComboBoxColumn col = new GridViewComboBoxColumn();
col.DataSource = DAL.ActiveDb.GetList<SalesRep>().ToList().OrderBy(x => x.RepName).Select(x => new { Id = x.Id, x.RepName });
col.DropDownStyle = RadDropDownStyle.DropDown;
col.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
col.DisplayMember = "RepName";
col.ValueMember = "Id";
col.FieldName = "RepId";
col.HeaderText = "Rep Name";
col.Width = 200;
//var t = gridColInfo.Where(x => x.ColumnName.ToLower() == "repid").FirstOrDefault();
//if (t != null)
//{
// col.Width = t.ColumnWidth;
//}
this.radGridBillwiseOpening.Columns.Add(col);

Entity Framework cycle of data

I have an Account object, which has many Transactions related to it.
In one method, I get all transactions for a particular account.
var transactionlines = (from p in Context.account_transaction
.Include("account_transaction_line")
// .Include("Account")
.Include("account.z_account_type")
.Include("account.institution")
.Include("third_party")
.Include("third_party.z_third_party_type")
.Include("z_account_transaction_type")
.Include("account_transaction_line.transaction_sub_category")
.Include("account_transaction_line.transaction_sub_category.transaction_category")
.Include("z_account_transaction_entry_type")
.Include("account_transaction_line.cost_centre")
where p.account_id == accountId
&& p.deleted == null
select p).ToList();
This is meant to return me a list of transactions, with their related objects. I then pass each object to a Translator, which translates them into data transfer objects, which are then passed back to my main application.
public TransactionDto TranslateTransaction(account_transaction source)
{
LogUserActivity("in TranslateTransaction");
var result = new TransactionDto
{
Id = source.id,
Version = source.version,
AccountId = source.account_id,
// Account = TranslateAccount(source.account, false),
ThirdPartyId = source.third_party_id,
ThirdParty = TranslateThirdParty(source.third_party),
Amount = source.transaction_amount,
EntryTypeId = source.account_transaction_entry_type_id,
EntryType = new ReferenceItemDto
{
Id = source.account_transaction_entry_type_id,
Description = source.z_account_transaction_entry_type.description,
Deleted = source.z_account_transaction_entry_type.deleted != null
},
Notes = source.notes,
TransactionDate = source.transaction_date,
TransactionTypeId = source.account_transaction_type_id,
TransactionType = new ReferenceItemDto
{
Id = source.z_account_transaction_type.id,
Description = source.z_account_transaction_type.description,
Deleted = source.z_account_transaction_type.deleted != null
}
};
... return my object
}
The problem is:
An account has Transactions, and a Transaction therefore belongs to an Account. It seems my translators are being called way too much, and reloading a lot of data because of this.
When I load my transaction object, it's 'account' property has a'transactions' propery, which has a list of all the transactions associated to that account. Each transaction then has an account property... and those account peroprties again, have a list of all the transactions... and on and on it goes.
Is there a way I can limit the loading to one level or something?
I have this set:
Context.Configuration.LazyLoadingEnabled = false;
I was hoping my 'Includes' would be all that is loaded... Don't load 'un-included' related data?
As requested, here is my TranslateAccount method:
public AccountDto TranslateAccount(account p, bool includeCardsInterestRateDataAndBalance)
{
LogUserActivity("in TranslateAccount");
if (p == null)
return null;
var result =
new AccountDto
{
Id = p.id,
Description = p.description,
PortfolioId = p.institution.account_portfolio_id,
AccountNumber = p.account_number,
Institution = TranslateInstitution(p.institution),
AccountType = new ReferenceItemDto
{
Id = p.account_type_id,
Description = p.z_account_type.description
},
AccountTypeId = p.account_type_id,
InstitutionId = p.institution_id,
MinimumBalance = p.min_balance,
OpeningBalance = p.opening_balance,
OpeningDate = p.opening_date
};
if (includeCardsInterestRateDataAndBalance)
{
// Add the assigned cards collection
foreach (var card in p.account_card)
{
result.Cards.Add(new AccountCardDto
{
Id = card.id,
AccountId = card.account_id,
Active = card.active,
CardHolderName = card.card_holder_name,
CardNumber = card.card_number,
ExpiryDate = card.expiry
});
}
// Populate the current interest rate
result.CurrentRate = GetCurrentInterestRate(result.Id);
// Add all rates to the account
foreach (var rate in p.account_rate)
{
result.Rates.Add(
new AccountRateDto
{
Id = rate.id,
Description = rate.description,
Deleted = rate.deleted != null,
AccountId = rate.account_id,
EndDate = rate.end_date,
Rate = rate.rate,
StartDate = rate.start_date
});
}
result.CurrentBalance = CurrentBalance(result.Id);
}
LogUserActivity("out TranslateAccount");
return result;
}
The entity framework context maintains a cache of data that has been pulled out of the database. Regardless of lazy loading being enabled/disabled, you can call Transaction.Account.Transactions[0].Account.Transactions[0]... as much as you want without loading anything else from the database.
The problem is not in the cyclical nature of entity framework objects - it is somewhere in the logic of your translation objects.

Error trying to loop through Linq query results

I need to pull any amount of records that correspond to a specific value (CourseCode), and insert these records into another table. This code works fine as long as the Linq code returns only one record, however if there is any more than that I get the following message:
An object with the same key already exists in the ObjectStateManager.
The existing object is in the Modified state. An object can only be
added to the ObjectStateManager again if it is in the added.
Below is my code:
if (_db == null) _db = new AgentResourcesEntities();
var prodCodes = from records in _db.CourseToProduct
where records.CourseCode == course.CourseCode
select records;
foreach (var pt in prodCodes.ToList())
{
agentProdTraining.SymNumber = symNumber;
agentProdTraining.CourseCode = course.CourseCode;
agentProdTraining.ProductCode = pt.ProductCode;
agentProdTraining.DateTaken = course.DateTaken;
agentProdTraining.Method = course.Method;
agentProdTraining.LastChangeOperator = requestor;
agentProdTraining.LastChangeDate = DateTime.Now;
agentProdTraining.DateExpired = course.ExpirationDate;
agentProdTraining.ProductCode = pt.ProductCode;
agentProdTraining.NoteId = pt.NoteId;
_db.AgentProductTraining.AddObject(agentProdTraining);
_db.SaveChanges();
PtAdded++;
EventLog.WriteEntry(sSource, "Product Training added", EventLogEntryType.Warning);
}
The loop is re-adding the same agentProdTraining object even though property values are changed. Create a new instance for each loop execution.
foreach (var pt in prodCodes.ToList())
{
var agentProdTraining = new AgentProductTraining();
agentProdTraining.SymNumber = symNumber;
agentProdTraining.CourseCode = course.CourseCode;
agentProdTraining.ProductCode = pt.ProductCode;
agentProdTraining.DateTaken = course.DateTaken;
agentProdTraining.Method = course.Method;
agentProdTraining.LastChangeOperator = requestor;
agentProdTraining.LastChangeDate = DateTime.Now;
agentProdTraining.DateExpired = course.ExpirationDate;
agentProdTraining.ProductCode = pt.ProductCode;
agentProdTraining.NoteId = pt.NoteId;
_db.AgentProductTraining.AddObject(agentProdTraining);
_db.SaveChanges();
PtAdded++;
EventLog.WriteEntry(sSource, "Product Training added", EventLogEntryType.Warning);
}

Entity Framework ObjectContext.SaveChanges fails on unique key column update

Consider very simple database table:
CREATE TABLE UkTest(
id int NOT NULL,
uk int NOT NULL
)
Primary Key on id
Unique Key on uk
Then add 2 rows:
INSERT INTO UkTest (id,uk) VALUES(1,1);
INSERT INTO UkTest (id,uk) VALUES(2,2);
Then do 2 tests.
OK:
var db = new Database1Entities();
var element1 = db.UkTest.FirstOrDefault(e => e.id == 1);
var element2 = db.UkTest.FirstOrDefault(e => e.id == 2);
element1.uk = 0;
element2.uk = 1; // overrides previous element1.uk value
var count = db.SaveChanges();
Fails (before test revert uk values to 1 and 2!):
var db = new Database1Entities();
var element1 = db.UkTest.FirstOrDefault(e => e.id == 1);
var element2 = db.UkTest.FirstOrDefault(e => e.id == 2);
element2.uk = 0;
element1.uk = 2; // overrides previous element2.uk value
var count = db.SaveChanges();
// Cannot insert duplicate key row in object 'dbo.UkTest' with unique index 'UK_UkTest'
See that ObjectContext.SaveChanges() checks rows in the order of primary index.
Is there any way to force own order?
Unless you call SaveChanges() twice, no, there is no way to control the order of SQL statements Entity Framework will send to the database. You could wrap the multiple SaveChanges() calls into an outer transaction to ensure still a transactional behaviour for the whole operation:
using (var scope = new TransactionScope())
{
using (var db = new Database1Entities())
{
var element1 = db.UkTest.FirstOrDefault(e => e.id == 1);
var element2 = db.UkTest.FirstOrDefault(e => e.id == 2);
element2.uk = 0;
db.SaveChanges();
element1.uk = 2;
db.SaveChanges();
}
scope.Complete();
}
Thanks to Slauma. I've found the solution. The key is to keep elements in several ObjectContext instances.
public class SavingElementsWithTransactionInOwnOrder
{
public void SaveElements ()
{
var db = new Database1Entities();
var element1 = db.UkTest.FirstOrDefault(e => e.id == 1);
element1.db = db;
db = new Database1Entities();
var element2 = db.UkTest.FirstOrDefault(e => e.id == 2);
element2.db = db;
element2.uk = 0;
element1.uk = 2;
var scope = new TransactionScope();
try{
element2.db.SaveChanges();
element1.db.SaveChanges();
scope.Complete();
}
finally{
scope.Dispose();
}
}
}
public partial class UkTest
{
public Database1Entities db { get; set; }
}

Update using LINQ to SQL

How can I update a record against specific id in LINQ to SQL?
LINQ is a query tool (Q = Query) - so there is no magic LINQ way to update just the single row, except through the (object-oriented) data-context (in the case of LINQ-to-SQL). To update data, you need to fetch it out, update the record, and submit the changes:
using(var ctx = new FooContext()) {
var obj = ctx.Bars.Single(x=>x.Id == id);
obj.SomeProp = 123;
ctx.SubmitChanges();
}
Or write an SP that does the same in TSQL, and expose the SP through the data-context:
using(var ctx = new FooContext()) {
ctx.UpdateBar(id, 123);
}
In the absence of more detailed info:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
DataClassesDataContext dc = new DataClassesDataContext();
FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);
fd.FatherName=txtFatherName.Text;
fd.FatherMobile=txtMobile.Text;
fd.FatherOccupation=txtFatherOccu.Text;
fd.MotherName=txtMotherName.Text;
fd.MotherOccupation=txtMotherOccu.Text;
fd.Phone=txtPhoneNo.Text;
fd.Address=txtAddress.Text;
fd.GuardianName=txtGardianName.Text;
dc.SubmitChanges();
I found a workaround a week ago. You can use direct commands with "ExecuteCommand":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.

Resources