Entity Framework cycle of data - linq

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.

Related

How can I retrieve Id of inserted entity using Entity framework Core?

I have a concern since as I am new to using EntityFramework Core, that if I add an object, that I still do not have the id generated by the database, sending the object to it in the transaction, I would add it automatically, this is my code ,
public async Task<ServiceResult<Common.Entities.Company>> SaveCompany(Domain.Models.Company companyModel, Domain.Models.Administrator administratoModel)
{
ServiceResult<Common.Entities.Company> serviceResult = new ServiceResult<Common.Entities.Company>();
try
{
if (user == null && companyExistsRnc == false)
{
Common.Entities.Company myCompany = new Common.Entities.Company
{
CompanyId = companyModel.CompanyId, // The id has not been generated yet,
CompanyName = companyModel.CompanyName,
Rnc = companyModel.Rnc,
CountryId = companyModel.Country.CountryId,
Telephone = companyModel.Telephone,
PersonContact = companyModel.PersonContact,
Address = companyModel.Address,
PhotoPath = companyModel.PhotoPath,
IsActive = false,
};
await _companyRepository.SaveCompany(myCompany); // this is the method that I add the company object to the database and do the savechanges
Common.Entities.User myUser = new Common.Entities.User
{
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
PhoneNumber = administratoModel.Telephone,
Email = administratoModel.Email,
UserName = administratoModel.Email,
IsActive = administratoModel.IsActive,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // here I send the my company object for when I do the savechanges, I think it will add it to me
};
await _userHelper.AddUserAsync(myUser, administratoModel.Password);
await _userHelper.AddUserToRoleAsync(myUser, Common.Core.UserType.Administrator.ToString());
Common.Entities.Administrator myAdministrator = new Common.Entities.Administrator
{
AdministratorId = administratoModel.AdministratorId,
FirstName = administratoModel.FirstName,
SecondName = administratoModel.SecondName,
FirstLastName = administratoModel.FirstLastName,
SecondLastName = administratoModel.SecondLastName,
GenderId = administratoModel.Gender.GenderId,
Email = administratoModel.Email,
Telephone = administratoModel.Telephone,
IsActive = true,
PhotoPath = administratoModel.PhotoPath,
UserTypeId = (short)Common.Core.UserType.Administrator,
Company = myCompany, // company object without the id
User = myUser, // user object without the id
};
await _administratorRepository.SaveAdministrator(myAdministrator);
serviceResult.Data = myCompany;
serviceResult.Message = "Compañia agregada!";
}
}
I am new to using entity framework core, and if in case I am wrong in what I am doing please indicate in which part I am doing it wrong, to correct, I await your comments and would appreciate the help,

decimal? with Left outer join gets null reference in LINQ

I am trying to do left outer join in LINQ for two vars but on selecting required coloumns, I get Object reference not set to an instance of an object error where I want Nullable decimal.
var FLS = (from ee in SumTillFYEnd
join es in SumTillFYStart on ee.Account equals es.Account into temp
from t in temp.DefaultIfEmpty()
select new
{
Account = ee.Account, // As of here it works
BeginDr = (t.DrStartCF == 0) ? (decimal?) null : t.DrStartCF // Here I get error Object reference not set to an instance of an object.
});
Some times SumTillFYEnd and some times SumTillFYStart becomes null. I want to join should work with default values, in case any one or both is null.
The problem is attempting to cast null to decimal?. You cannot ever directly cast null to another type, nullable or not. That will always cause a NullReferenceException. What you want instead is default. In other words, replace:
(decimal?)null
With
default(decimal?)
I solved this using a default class.
The reason I am seeing is that decimal can not be null so it either needs to set for a default value either 0 or decimal.MinValue
So, you require to have default class for SumTillFYStart like
var defaultSumTillFYStart = new SumTillFYStart { Account = string.Empty, DrStartCF =0};
With above in context, then in your piece of code replace
from t in temp.DefaultIfEmpty()
with this
from t in temp.DefaultIfEmpty(defaultSumTillFYStart)
I have a linqPad working written below but for different subset; I think it will help somebody:
void Main()
{
List<Debtor> debtors = new List<Debtor>();
List<SecurityHolding> holdings = new List<SecurityHolding>();
//Initialize Debtor
debtors.Add(new Debtor(){
AccountId = "J1",
OutstandingValue = 501.95M
});
debtors.Add(new Debtor(){
AccountId = "J2",
OutstandingValue = 75.68M
});
debtors.Add(new Debtor(){
AccountId = "J3",
OutstandingValue = 100.01M
});
//Initialize Security Holding
holdings.Add(new SecurityHolding(){
AccountId = "J2",
SecurityHoldingValue = 100M
});
holdings.Add(new SecurityHolding(){
AccountId = "J3",
SecurityHoldingValue = 200M
});
var defaultHolding = new SecurityHolding { AccountId= string.Empty, SecurityHoldingValue = 0};
var result = (from d in debtors
join p in holdings
on d.AccountId equals p.AccountId into temp
from t in temp.DefaultIfEmpty(defaultHolding)
select new
{
AccountId = d.AccountId,
OutstandingValue = d.OutstandingValue,
HoldingValue = (decimal?)t.SecurityHoldingValue
});
result.Dump();
}
// Define other methods and classes here
public class Debtor
{
public string AccountId {get;set;}
public decimal OutstandingValue {get;set;}
}
public class SecurityHolding
{
public string AccountId {get;set;}
public decimal SecurityHoldingValue {get;set;}
}
Here the output:

Calling 'Read' when the data reader is closed is not a valid operation error using Entity Framework database first approach

I am creating a Web API that will fetch information from a table using Entity Framework database-first approach using stored procedures. ListAllTeams_Result is the complex type object created in Entity Framework. I am looping through the import function GetAllTeams() and populating the complex type. I am getting an error in my business layer when trying to access the data access layer
The error that I am getting is the following code
var team = _teamRepository.GetAllTeams();
The result of the query cannot be enumerated more than once.
Note: this error is in the inner stack and doesn't stop the application from executing
foreach (var t in team)
Calling 'Read' when the data reader is closed is not a valid operation.
Note : This stops execution
Business Layer
public IEnumerable<TeamDto> GetTeam()
{
var team = _teamRepository.GetAllTeams();
if (team != null)
{
foreach (var t in team.ToList())
{
yield return Mapper.Map<TeamDto>(t);
}
}
yield break;
}
DataAccess layer:
public IEnumerable<ListAllTeams_Result> GetAllTeams()
{
using (var mcrContext = new MCREntities())
{
return (from team in mcrContext.ListAllTeams("")
select new ListAllTeams_Result
{
TeamID = team.TeamID,
TeamDescription = team.TeamDescription,
CountryCode = team.CountryCode,
CreatedBy = team.CreatedBy,
CreatedDate = team.CreatedDate,
ModifiedBy = team.ModifiedBy,
ModifiedDate = team.ModifiedDate
});
}
}
I have found what the problem is. I had to add ToList in the return
using (var mcrContext = new MCREntities())
{
return (from team in mcrContext.ListAllTeams("")
select new ListAllTeams_Result
{
TeamID = team.TeamID,
TeamName = team.TeamName,
TeamDescription = team.TeamDescription,
CountryCode = team.CountryCode,
CreatedBy = team.CreatedBy,
CreatedDate = team.CreatedDate,
ModifiedBy = team.ModifiedBy,
ModifiedDate = team.ModifiedDate
}).ToList();
}

How can improve this Linq query expressions performance?

public bool SaveValidTicketNos(string id,string[] ticketNos, string checkType, string checkMan)
{
bool result = false;
List<Carstartlistticket>enties=new List<Carstartlistticket>();
using (var context = new MiniSysDataContext())
{
try
{
foreach (var ticketNo in ticketNos)
{
Orderticket temp = context.Orderticket.ByTicketNo(ticketNo).SingleOrDefault();
if (temp != null)
{
Ticketline ticketline= temp.Ticketline;
string currencyType = temp.CurrencyType;
float personAllowance=GetPersonCountAllowance(context,ticketline, currencyType);
Carstartlistticket carstartlistticket = new Carstartlistticket()
{
CsltId = Guid.NewGuid().ToString(),
Carstartlist = new Carstartlist(){CslId = id},
LeaveDate = temp.LeaveDate,
OnPointName = temp.OnpointName,
OffPointName = temp.OffpointName,
OutTicketMan = temp.OutBy,
TicketNo = temp.TicketNo,
ChekMan = checkMan,
Type = string.IsNullOrEmpty(checkType)?(short?)null:Convert.ToInt16(checkType),
CreatedOn = DateTime.Now,
CreatedBy = checkMan,
NumbserAllowance = personAllowance
};
enties.Add(carstartlistticket);
}
}
context.BeginTransaction();
context.Carstartlistticket.InsertAllOnSubmit(enties);
context.SubmitChanges();
bool changeStateResult=ChangeTicketState(context, ticketNos,checkMan);
if(changeStateResult)
{
context.CommitTransaction();
result = true;
}
else
{
context.RollbackTransaction();
}
}
catch (Exception e)
{
LogHelper.WriteLog(string.Format("CarstartlistService.SaveValidTicketNos({0},{1},{2},{3})",id,ticketNos,checkType,checkMan),e);
context.RollbackTransaction();
}
}
return result;
}
My code is above. I doubt these code have terrible poor performance. The poor performance in the point
Orderticket temp = context.Orderticket.ByTicketNo(ticketNo).SingleOrDefault();
,actually, I got an string array through the method args,then I want to get all data by ticketNos from database, here i use a loop,I know if i write my code like that ,there will be cause performance problem and it will lead one more time database access,how can avoid this problem and improve the code performance,for example ,geting all data by only on databse access
I forget to tell you the ORM I use ,en ,the ORM is PlinqO based NHibernate
i am looking forward to having your every answer,thank you
using plain NHibernate
var tickets = session.QueryOver<OrderTicket>()
.WhereRestrictionOn(x => x.TicketNo).IsIn(ticketNos)
.List();
short? type = null;
short typeValue;
if (!string.IsNullOrEmpty(checkType) && short.TryParse(checkType, out typeValue))
type = typeValue;
var entitiesToSave = tickets.Select(ticket => new Carstartlistticket
{
CsltId = Guid.NewGuid().ToString(),
Carstartlist = new Carstartlist() { CslId = id },
LeaveDate = ticket.LeaveDate,
OnPointName = ticket.OnpointName,
OffPointName = ticket.OffpointName,
OutTicketMan = ticket.OutBy,
TicketNo = ticket.TicketNo,
ChekMan = checkMan,
CreatedOn = DateTime.Now,
CreatedBy = checkMan,
Type = type,
NumbserAllowance = GetPersonCountAllowance(context, ticket.Ticketline, ticket.CurrencyType)
});
foreach (var entity in entitiesToSave)
{
session.Save(entity);
}
to enhance this further try to preload all needed PersonCountAllowances

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);
}

Resources