Get all business units - c#

I am trying to retrieve all business units from CRM 2013.
Tried the following query
var query = _serviceContext.BusinessUnitSet
.Where(b => b.EntityState == 0)
.Select(x => new
{
Name = x.Name,
Id = x.Id
}
)
.ToList();
Using this query I am receiving an error just stating:
{System.ServiceModel.FaultCode} {attributeName} {System.Collections.Generic.SynchronizedReadOnlyCollection<System.ServiceModel.FaultReasonText>}
When googling on the subject I found information about how to retrieve single business units (which seems to be different from retrieving a "normal" entity), but not how to get them all (link).
Any help as to how I would retrieve all business units would be much appreciated.

Try this using QueryExpression
public class BusinessUnit
{
public Guid Id { get; set; }
public String Name { get; set; }
}
public void GetAllBusinessUnits(Action<QueryExpression> queryModifier = null)
{
foreach (BusinessUnit m in RetrieveAllBusinessUnit(this.Service, 1000, queryModifier))
{
//Console.WriteLine(m.Name);
}
}
public static IEnumerable<BusinessUnit> RetrieveAllBusinessUnit(IOrganizationService service, int count = 1000, Action<QueryExpression> queryModifier = null)
{
QueryExpression query = new QueryExpression("businessunit")
{
ColumnSet = new ColumnSet("businessunitid", "name"),
PageInfo = new PagingInfo()
{
Count = count,
PageNumber = 1,
PagingCookie = null,
}
};
if (queryModifier != null)
{
queryModifier(query);
}
while (true)
{
EntityCollection results = service.RetrieveMultiple(query);
foreach (Entity e in results.Entities)
{
yield return new BusinessUnit()
{
Id = e.GetAttributeValue<Guid>("businessunitid"),
Name = e.GetAttributeValue<String>("name")
};
}
if (results.MoreRecords)
{
query.PageInfo.PageNumber++;
query.PageInfo.PagingCookie = results.PagingCookie;
}
else
{
yield break;
}
}
}

I presume you want to get all active business units from system. So you must use IsDisabled property to get them. The property you use EntityState is used for tracking the entity state in context, not to indicate state of entity in CRM. See BusinessUnit Entity for more info about BU entity.

Related

Map list manually from context

Initially I was using automapper for this but its seems way harder for me to implement it.
Basically, I just want to return an empty list instead of null values. I can do this on projects level but not on teammates level. The API must not return a null because the UI that consumes it will have an error.
Sample of my implementation below:
Projects = !Util.IsNullOrEmpty(x.Projects) ? x.Projects : new List<ProjectsDto>(),
Ill highly appreciate if someone can guide me on how to manually map this with null/empty checking.
If you can also provide and example using automapper that too will be very helpful.
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public List<ProjectsDto> Projects { get; set; }
}
public class ProjectsDto
{
public string Status { get; set; }
public List<TeammatesDto> Teammates { get; set; }
}
public class TeammatesDto
{
public string TeammateName { get; set; }
public string PreviousProject { get; set; }
}
//Get by Id
var employee = await _context.Employees
.Where(x => x.id.Equals(request.Id)
.FirstOrDefaultAsync(cancellationToken);
//Map employee
EmployeeDto ret = new EmployeeDto()
{
Id = employee.id,
Name = employee.Name,
Projects = null //TODO: map manually
}
//Get all employees
var employees = await _context.Employees.AsNoTracking()
.ToListAsync(cancellationToken);
//Map here
IList<EmployeeDto> list = new List<EmployeeDto>();
foreach (var x in employees)
{
EmployeeDto dto = new EmployeeDto()
{
Id = x.id,
Name = x.Name,
Projects = null //TODO: map manually
};
list.Add(dto);
}
return list;
Instead of materializing full entities, do the following:
var query = _context.Employees
.Select(e = new EmployeeDto
{
Id = e.id,
Name = e.Name,
Projects = e.Projects.Select(p => new ProjectDto
{
Status = p.Status,
Templates = p.Templates.Select(t => new TemplateDto
{
TeammateName = t.TeammateName,
PreviousProject = t.PreviousProject
}).ToList()
}).ToList()
}
);
var result = await query.ToListAsync();

How to map multiple source members so that propertyMap.SourceMembers yields these multiple source members?

I want to reuse the intialized mappings of the c# Automapper (using version 6.2.2) by looping through all mapped properties.
Let's suppose I have the following:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonDto
{
public int Id { get; set; }
public string FullName { get; set; }
}
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Person, PersonDto>()
.ForMember(dest => dest.FullName,
opt => opt.MapFrom(src => src.FirstName + " " + src.LastName));
};
The loop for Id behaves as expected:
var map = AutoMapper.Mapper.Configuration.FindTypeMapFor<Person, PersonDto>();
foreach (var propertyMap in map.GetPropertyMaps())
{
var destProp = propertyMap.DestinationProperty.Name; // = "Id"
var sourceMember = propertyMap.SourceMember.Name; // = "Id"
var sourceMembers = propertyMap.SourceMembers; // Count = 1
}
But when I loop through the FullName property mapping, I want to achieve that the propertyMap.SourceMembers results in the two SourceMembers FirstName and LastName:
var map = AutoMapper.Mapper.Configuration.FindTypeMapFor<Person, PersonDto>();
foreach (var propertyMap in map.GetPropertyMaps())
{
var destProp = propertyMap.DestinationProperty.Name; // = "FullName"
var sourceMember = propertyMap.SourceMember.Name; // = "LastName" (I don't care)
var sourceMembers = propertyMap.SourceMembers; // Count = 0 (want to achieve 2 for FirstName and LastName)
}
My goal is to create an automated similar mapping for an orderBy functionality based on the initialized automapper mappings. So I need to know (a) the order and (b) the sourceMembers. In the above case I want get the mapping for FullName from its source members FirstName and LastName (in this order).
Is it somehow possible to correctly register multiple source members so that propertyMap.SourceMembers yields all mapped source members? If yes, what should the map initialization look like?
PS: I don't want to write the orderBy mappings by hand, since I already have mappings thanks to automapper.
Thanks to Lucian Bargaoanu, I developed the following dirty workaround.
Please note that this is the first time that I get in touch with interpreting expressions, so bear with me the quality of my solution:
var map = AutoMapper.Mapper.Configuration.FindTypeMapFor<Person, PersonDto>();
foreach (var propertyMap in map.PropertyMaps)
{
var destProp = propertyMap.DestinationMember.Name; // = "FullName"
var sourceMember = propertyMap.SourceMember?.Name; // = "LastName" (I don't care)
var sourceMembers = propertyMap.SourceMembers.ToList();
if (sourceMembers.Count() == 0)
{
ResolveSourceMembersInOrder(sourceMembers,
propertyMap.CustomMapExpression.Body as BinaryExpression);
}
// sourceMembers now yield the two desired sourceMembers "FirstName" and "LastName"
}
public static void ResolveSourceMembersInOrder(List<MemberInfo> memberInfos, BinaryExpression expression)
{
if (memberInfos == null)
{
memberInfos = new List<MemberInfo>();
}
if (expression == null)
{
return;
}
var left = expression.Left;
if (left.NodeType == ExpressionType.MemberAccess)
{
memberInfos.Add(MemberVisitor.GetMemberPath(left).FirstOrDefault());
}
else
{
ResolveSourceMembersInOrder(memberInfos, left as BinaryExpression);
}
var right = expression.Right;
if (right.NodeType == ExpressionType.MemberAccess)
{
memberInfos.Add(MemberVisitor.GetMemberPath(right).FirstOrDefault());
}
else
{
ResolveSourceMembersInOrder(memberInfos, right as BinaryExpression);
}
}

Unable to display LINQ query output values from controller to view

Controller
public ActionResult Track(string awb)
{
ViewBag.Title = "Track Your Shipment";
ViewBag.ErrorMessage = string.Empty;
ViewBag.ShipmentNo = awb;
FLCourierDetail trackOutput = new FLCourierDetail();
if (awb != null)
{
trackOutput = db.FL_CourierDetail.SingleOrDefault(fLCourierDetail => fLCourierDetail.AWBNumber == awb);
if (trackOutput != null)
{
var courierId = db.FL_CourierDetail.Where(s => s.AWBNumber == awb).Select(s => s.Courier);
var currentStatus = (from c in db.FL_CourierDetail
join s in db.FL_CourierStatus
on c.Courier equals s.CourierId
where c.AWBNumber == awb
select new { awb = c.AWBNumber, staus = s.StatusId, updated = s.StatusId, remark = s.Remark }).ToList();
ViewBag.CurrentStatus = currentStatus;
}
else
{
ViewBag.ErrorMessage = "Shipment number not found.";
}
}
else
{
ViewBag.ErrorMessage = "Please provide valid Shipment number.";
}
return View(trackOutput);
}
View
<div class="col-md-6">
#{
var status = ViewBag.CurrentStatus;
foreach (var item in status)
{
<p>#item</p>
}
}
</div>
If I iterate using foreach or if loop I am able to see the data in debug, but I am not able to write in html.
Debug
Web Page
Error
I am not able to read each value like awb, status, date etc.
Did I miss anything here?
The query result is an anonymous class, within the loop, each item is an object and thus the exception, object has now awb property.
One way to solve this is by defining a class:
public class Status {
public string awb { get; set; }
public int staus { get; set; }
public int updated { get; set; }
public string remark { get; set; }
}
Then your select would look like:
... select new Status { awb = c.AWBNumber, staus = s.StatusId, updated = s.StatusId, remark = s.Remark }).ToList();
Then, within the View:
var status = (List<Status>) ViewBag.CurrentStatus;
Another possible solution is to use strongly typed view model
Firstly, you could create a Model class for returned data;
var currentStatus = (from c in db.FL_CourierDetail
join s in db.FL_CourierStatus
on c.Courier equals s.CourierId
where c.AWBNumber == awb
select new CurrentStatus { awb = c.AWBNumber, staus = s.StatusId, updated = s.StatusId, remark = s.Remark }).ToList();
public class CurrentStatus
{
public string awb { get; set; }
public int staus { get; set; }
public int updated { get; set; }
public string remark { get; set; }
}
Secondly, you can't get output an entire object, you should specify properties which you want to display;
<div class="col-md-6">
#{
var status = (List<CurrentStatus>) ViewBag.CurrentStatus;
foreach (var item in status)
{
<p>#item.awb</p>
<p>#item.staus</p>
<p>#item.updated</p>
<p>#item.remark</p>
}
}
</div>
This is really strange, but in console application the following code actually works:
dynamic even = new List<int> { 1, 2, 3, 4 }
.Where(x => x % 2 == 0)
.Select((x, index) => new { Position = index, Num = x });
// Output:
// Position: 0, Number: 2
// Position: 1, Number: 4
foreach (dynamic item in even)
{
Console.WriteLine($"Position: {item.Position}, Number: {item.Num}");
}
However, in ASP.NET ths doesn't work, and I don't really understand because ViewBag is dynamic, too.
UPDATE
Same question was asked here. A quote from there:
You're returning an instance of an anonymous type. If you weren't using dynamic, your only choice here would be to return an object - the anonymous type is unknown outside of your own function. If you had a variable of type object, you'd get a compile time error that it doesn't have a LogoName property. All you've done with dynamic is defer exactly the same lookup rules until runtime. At runtime, the best type that can be determined is object.
As this answer states, the following must not work, but it works:
static void DoWork()
{
dynamic evens = GetEvens();
foreach (dynamic item in evens)
Console.WriteLine($"Position: {item.Position}, Number: {item.Num}");
}
static dynamic GetEvens() =>
new List<int> { 1, 2, 3, 4 }
.Where(x => x % 2 == 0)
.Select((x, index) => new { Position = index, Num = x });
In this case I return dynamic. However, the code work correctly.

Insert relations very slow

I have to insert multiple relations and having issues with the Context.SaveChanges action which takes like forever to complete. I already tried multiple ways to add these entities to database but nothing seems to help me out.
My models are build in the following way:
public class Agreement : GdSoftDeleteEntity
{
public DateTime Date { get; set; }
public AgreementType AgreementType { get; set; }
public virtual ICollection<PersonAgreementRelation> PersonAgreementRelations { get; set; }
public virtual ICollection<ImageSearchAppointment> ImageSearchAppointments { get; set; }
}
public class Person : GdSoftDeleteEntity
{
public string Name { get; set; }
public string FirstName { get; set; }
// E-mail is in identityuser
//public string EmailAddress { get; set; }
public virtual PersonType PersonType { get; set; }
public virtual ICollection<PersonAgreementRelation> PersonAgreementRelations { get; set; }
public virtual ICollection<PersonPersonRelation> PersonMasters { get; set; }
public virtual ICollection<PersonPersonRelation> PersonSlaves { get; set; }
}
public class PersonAgreementRelation : GdSoftDeleteEntity
{
public int PersonId { get; set; }
public virtual Person Person { get; set; }
public int AgreementId { get; set; }
public virtual Agreement Agreement { get; set; }
public virtual PersonAgreementRole PersonAgreementRole { get; set; }
}
public class ImageSearchAppointment : GdSoftDeleteEntity
{
public string Name { get; set; }
public bool ShowResultsToCustomer { get; set; }
public bool HasImageFeed { get; set; }
public int AgreementId { get; set; }
public virtual Agreement Agreement { get; set; }
public Periodicity Periodicity { get; set; }
public PeriodicityCategory PeriodicityCategory { get; set; }
public virtual ICollection<ImageSearchCommand> ImageSearchCommands { get; set; }
public virtual ICollection<ImageSearchAppointmentWebDomainWhitelist> ImageSearchAppointmentWebDomainWhitelists { get; set; }
public virtual ICollection<ImageSearchAppointmentWebDomainExtension> ImageSearchAppointmentWebDomainExtensions { get; set; }
}
public class ImageSearchCommand : GdSoftDeleteEntity
{
public int ImageSearchAppointmentId { get; set; }
public virtual ImageSearchAppointment ImageSearchAppointment { get; set; }
public int? ImageSearchAppointmentCredentialsId { get; set; }
public virtual ImageSearchAppointmentCredentials ImageSearchAppointmentCredentials { get; set; }
public DateTime Date { get; set; }
//public bool Invoiced { get; set; }
public int NumberOfImages { get; set; }
public DateTime ImageCollectionProcessedDate { get; set; }
public virtual ICollection<ImageSearchExecution> ImageSearchExecutions { get; set; }
}
In my service, I have written following code:
public int AddAgreement(int personId, AgreementDto agreementDto)
{
Context.Configuration.LazyLoadingEnabled = false;
//var person = Context.Persons.SingleOrDefault(el => el.Id == personId);
var person = Context.Persons
.SingleOrDefault(x => x.Id == personId);
if (person == null)
{
throw new GraphicsDetectiveInvalidDataTypeException($"No person found for Id: {personId}");
}
if (agreementDto == null)
{
throw new GraphicsDetectiveInvalidDataTypeException("Invalid agreementDto");
}
//TODO: Check if OKAY!!!
if (agreementDto.ImageSearchAppointmentDto.Count == 0)
{
throw new GraphicsDetectiveInvalidDataTypeException("Count of imagesearchappointments can't be lower than 0");
}
//set agreement properties
var agreement = new Agreement
{
Date = agreementDto.DateTime,
AgreementType = AgreementType.WwwImageSearch,
//ImageSearchAppointments = new List<ImageSearchAppointment>(),
//IsDeleted = false
};
Context.Agreements.Add(agreement);
Context.SaveChanges();
//var personAdminId = Context.Users.Single(x => x.Email == ConfigurationManager.AppSettings["DefaultGdAdminEmail"]).PersonId;
// Dit werkt niet. Moet in 2 stappen
//set personagreementrelations for new agreement
var adminEmail = ConfigurationManager.AppSettings["DefaultGdAdminEmail"];
var personAdminId = Context.Users
.SingleOrDefault(x => x.Email == adminEmail)
.PersonId;
var personPmId = Context.Persons.Single(x => x.Name == "My name").Id;
var personAgreementRelations = new List<PersonAgreementRelation>()
{
new PersonAgreementRelation
{
AgreementId = agreement.Id,
PersonId = personId,
PersonAgreementRole = PersonAgreementRole.Client,
},
new PersonAgreementRelation
{
AgreementId = agreement.Id,
PersonAgreementRole = PersonAgreementRole.Supplier,
PersonId = personPmId,
},
new PersonAgreementRelation
{
AgreementId = agreement.Id,
PersonAgreementRole = PersonAgreementRole.Admin,
PersonId = personAdminId,
}
};
foreach (var personAgreementRelation in personAgreementRelations)
{
Context.PersonAgreementRelations.Add(personAgreementRelation);
}
Context.Configuration.ValidateOnSaveEnabled = false;
Context.Configuration.AutoDetectChangesEnabled = false;
Context.SaveChanges();
Context.Configuration.ValidateOnSaveEnabled = true;
Context.Configuration.AutoDetectChangesEnabled = true;
Context.Configuration.LazyLoadingEnabled = true;
return agreement.Id;
}
public void AddFirstImageSearchAppointmentToAgreement(int agreementId, ImageSearchAppointmentDto imageSearchAppointmentDto)
{
Context.Configuration.LazyLoadingEnabled = false;
var agreement = Context.Agreements.SingleOrDefault(x => x.Id == agreementId);
if (agreement == null)
{
throw new GraphicsDetectiveInvalidDataTypeException($"No agreement found for id {agreementId}");
}
var appointmentType = imageSearchAppointmentDto;
if (appointmentType == null)
{
throw new GraphicsDetectiveInvalidDataTypeException($"No valid imageSearchAppointment");
}
if (appointmentType.ImageSearchCommandDto.Count == 0)
{
throw new GraphicsDetectiveInvalidDataTypeException("No imageSearchCommand");
}
var imageSearchAppointment = new ImageSearchAppointment
{
AgreementId = agreement.Id,
Agreement = agreement,
Name = appointmentType.Name,
Periodicity = appointmentType.Periodicity,
PeriodicityCategory = appointmentType.PeriodicityCategory,
ShowResultsToCustomer = appointmentType.ShowResultsToCustomer,
ImageSearchAppointmentWebDomainExtensions = new List<ImageSearchAppointmentWebDomainExtension>(),
ImageSearchCommands = new List<ImageSearchCommand>(),
ImageSearchAppointmentWebDomainWhitelists = new List<ImageSearchAppointmentWebDomainWhitelist>(),
IsDeleted = false
};
var imageSearchCommandDto = appointmentType.ImageSearchCommandDto.Single();
var imageSearchCommand = new ImageSearchCommand()
{
ImageSearchAppointment = imageSearchAppointment,
Date = imageSearchCommandDto.Date,
NumberOfImages = imageSearchCommandDto.NumberOfImages,
ImageCollectionProcessedDate = imageSearchCommandDto.ImageCollectionProcessedDate,
IsDeleted = false
};
if (imageSearchCommandDto.ImageSearchAppointmentCredentialsDto != null)
{
imageSearchCommand.ImageSearchAppointmentCredentials = new ImageSearchAppointmentCredentials
{
FtpProfileType = imageSearchCommandDto.ImageSearchAppointmentCredentialsDto.FtpProfileType,
Location = imageSearchCommandDto.ImageSearchAppointmentCredentialsDto.Location,
Username = imageSearchCommandDto.ImageSearchAppointmentCredentialsDto.Username,
Password = imageSearchCommandDto.ImageSearchAppointmentCredentialsDto.Password,
UsePassive = imageSearchCommandDto.ImageSearchAppointmentCredentialsDto.UsePassive,
IsDeleted = false
};
}
imageSearchAppointment.ImageSearchCommands.Add(imageSearchCommand);
if (!imageSearchAppointment.ShowResultsToCustomer)
{
var webDomainExtensions = appointmentType.WebDomainExtensionDtos
.Select(x => new ImageSearchAppointmentWebDomainExtension()
{
ImageSearchAppointment = imageSearchAppointment,
WebDomainExtensionId = x.Id
})
.ToList();
imageSearchAppointment.ImageSearchAppointmentWebDomainExtensions = webDomainExtensions;
}
Context.ImageSearchAppointments.Add(imageSearchAppointment);
Context.SaveChanges();
Context.Configuration.LazyLoadingEnabled = true;
}
I used dotTrace to profile these functions and it takes about 9 minutes to add the new entities to my database.
The database is an Azure SQL database, tier S3
I tried the proposed solution and adapted my code as follow:
public int AddAgreement(int personId, AgreementDto agreementDto)
{
var agreementId = 0;
using (var context = new GdDbContext())
{
GdDbConfiguration.SuspendExecutionStrategy = true;
context.Configuration.LazyLoadingEnabled = true;
//var person = Context.Persons.SingleOrDefault(el => el.Id == personId);
var person = context.Persons
.SingleOrDefault(x => x.Id == personId);
if (person == null)
{
throw new GraphicsDetectiveInvalidDataTypeException($"No person found for Id: {personId}");
}
//var personAdminId = Context.Users.Single(x => x.Email == ConfigurationManager.AppSettings["DefaultGdAdminEmail"]).PersonId;
// Dit werkt niet. Moet in 2 stappen
//set personagreementrelations for new agreement
var adminEmail = ConfigurationManager.AppSettings["DefaultGdAdminEmail"];
var personAdminId = context.Users
.Where(x => x.Email == adminEmail)
.Include(x => x.Person)
.First()
.Person.Id;
var personPmId = context.Persons.First(x => x.Name == "My name").Id;
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
if (agreementDto == null)
{
throw new GraphicsDetectiveInvalidDataTypeException("Invalid agreementDto");
}
//TODO: Check if OKAY!!!
if (agreementDto.ImageSearchAppointmentDto.Count == 0)
{
throw new GraphicsDetectiveInvalidDataTypeException("Count of imagesearchappointments can't be lower than 0");
}
//set agreement properties
var agreement = new Agreement
{
Date = agreementDto.DateTime,
AgreementType = AgreementType.WwwImageSearch,
//ImageSearchAppointments = new List<ImageSearchAppointment>(),
//IsDeleted = false
};
context.Agreements.Add(agreement);
//Context.SaveChanges();
var personAgreementRelations = new List<PersonAgreementRelation>()
{
new PersonAgreementRelation
{
//Agreement = agreement,
AgreementId = agreement.Id,
PersonId = personId,
//Person = person,
PersonAgreementRole = PersonAgreementRole.Client,
//IsDeleted = false
},
new PersonAgreementRelation
{
//Agreement = agreement,
AgreementId = agreement.Id,
PersonAgreementRole = PersonAgreementRole.Supplier,
PersonId = personPmId,
//Person = personPm,
//IsDeleted = false
},
new PersonAgreementRelation
{
//Agreement = agreement,
AgreementId = agreement.Id,
PersonAgreementRole = PersonAgreementRole.Admin,
PersonId = personAdminId,
//Person = personAdmin,
}
};
foreach (var personAgreementRelation in personAgreementRelations)
{
context.PersonAgreementRelations.Add(personAgreementRelation);
}
//agreement.PersonAgreementRelations = personAgreementRelations;
//Context.Agreements.Add(agreement);
context.Configuration.ValidateOnSaveEnabled = false;
context.Configuration.AutoDetectChangesEnabled = false;
//await Context.SaveChangesAsync();
context.SaveChanges();
dbContextTransaction.Commit();
//await Task.Run(async () => await Context.SaveChangesAsync());
context.Configuration.ValidateOnSaveEnabled = true;
context.Configuration.AutoDetectChangesEnabled = true;
context.Configuration.LazyLoadingEnabled = false;
agreementId = agreement.Id;
}
catch (Exception ex)
{
dbContextTransaction.Rollback();
throw ex;
}
}
GdDbConfiguration.SuspendExecutionStrategy = false;
}
return agreementId;
}
but it's taking as much time as before
You can follow below mentioned suggestions to improve the performance of above methods.
Use FirstOrDefault() instead of SingleOrDefault().FirstOrDefault() is the fastest method.
I can see that you have used Context.SaveChanges() method number of times on the same method.That will degrade the performnce of the method.So you must avoid that.Instead of use Transactions.
Like this : EF Transactions
using (var context = new YourContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
// your operations here
context.SaveChanges(); //this called only once
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
You can think about the implementaion of stored procedure if above will not give the enough improvement.
There are some performance issues with your code
Add Performance
foreach (var personAgreementRelation in personAgreementRelations)
{
Context.PersonAgreementRelations.Add(personAgreementRelation);
}
Context.Configuration.ValidateOnSaveEnabled = false;
Context.Configuration.AutoDetectChangesEnabled = false;
You add multiple entities then disabled AutoDetectChanges. You normally do the inverse
Depending on the number of entities in your context, it can severely hurt your performance
In the method "AddFirstImageSearchAppointmentToAgreement", it seems you use an outside context which can be very bad if it contains already multiple thousands of entities.
See: Improve Entity Framework Add Performance
Badly used, adding an entity to the context with the Add method take more time than saving it in the database!
SaveChanges vs. Bulk Insert vs. BulkSaveChanges
SaveChanges is very slow. For every record to save, a database round-trip is required. This is particularly the case for SQL Azure user because of the extra latency.
Some library allows you to perform Bulk Insert
See:
Entity Framework Bulk Insert Library
Entity Framework Bulk SaveChanges Library
Disclaimer: I'm the owner of the project Entity Framework Extensions
This library has a BulkSaveChanges features. It works exactly like SaveChanges but WAY FASTER!
// Context.SaveChanges();
Context.BulkSaveChanges();
EDIT: ADD additional information #1
I pasted my new code in Pastebin: link
Transaction
Why starting a transaction when you select your data and add entities to your context? It simply a VERY bad use of a transaction.
A transaction must be started as late as possible. In since BulkSaveChanges is already executed within a transaction, there is no point to create it.
Async.Result
var personAdminId = context.Users.FirstOrDefaultAsync(x => x.Email == adminEmail).Result.PersonId;
I don't understand why you are using an async method here...
In best case, you get similar performance as using non-async method
In worse case, you suffer from some performance issue with async method
Cache Item
var adminEmail = ConfigurationManager.AppSettings["DefaultGdAdminEmail"];
var personAdminId = context.Users.FirstOrDefaultAsync(x => x.Email == adminEmail).Result.PersonId;
I don't know how many time you call the AddAgreement method, but I doubt the admin will change.
So if you call it 10,000 times, you make 10,000 database round-trip to get the same exact value every time.
Create a static variable instead and get the value only once! You will for sure save a lot of time here
Here is how I normally handle static variable of this kind:
var personAdminId = My.UserAdmin.Id;
public static class My
{
private static User _userAdmin;
public static User UserAdmin
{
get
{
if (_userAdmin == null)
{
using (var context = new GdDbContext())
{
var adminEmail = ConfigurationManager.AppSettings["DefaultGdAdminEmail"];
_userAdmin = context.Users.FirstOrDefault(x => x.Email == adminEmail);
}
}
return _userAdmin;
}
}
}
LazyLoadingEnabled
In the first code, you have LazyLoadingEnabled to false but not in your Pastebin code,
Disabling LazyLoading can help a little bit since it will not create a proxy instance.
Take 10m instead of 9m
Let me know after removing the transaction and disabling again LazyLoading if the performance is a little bit better.
The next step will be to know some statistics:
Around how many time the AddAgreement method is invoked
Around how many persons do you have in your database
Around how many entities in average is Saved by the AddAgreement method
EDIT: ADD additional information #2
Currently, the only way to improve really the performance is by reducing the number of database round-trip.
I see you are still searching the personAdminId every time. You could save maybe 30s to 1 minute just here by caching this value somewhere like a static variable.
You still have not answered the three questions:
Around how many time the AddAgreement method is invoked
Around how many persons do you have in your database
Around how many entities in average is Saved by the AddAgreement method
The goal of theses questions is to understand what's slow!
By example, if you call the AddAgreement method 10,000 times and you only have 2000 persons in the database, you are probably better to cache in two dictionary theses 2000 persons to save 20,000 database round-trip (Saving one to two minutes?).

Copy Entity Framework Object

I have a EF4.1 class X and I want to make copy of that plus all its child records.
X.Y and X.Y.Z
Now if I do the following it returns error.
The property 'X.ID' is part of the object's key information and cannot be modified.
public void CopyX(long ID)
{
var c = db.Xs.Include("Y").Include("W").Include("Y.Z").SingleOrDefault(x => x.ID == ID);
if (c != null)
{
c.ID = 0;
c.Title = "Copy Of " + c.Title;
for (var m = 0; m < c.Ys.Count; m++)
{
c.Ys[m].ID = 0;
c.Ys[m].XID=0-m;
for (var p = 0; p < c.Ys[m].Zs.Count; p++)
{
c.Ys[m].Zs[p].XID = 0 - m;
c.Ys[m].Zs[p].ID = 0 - p;
}
}
for (var i = 0; i < c.Ws.Count; i++)
{
c.Ws[i].ID = 0 - i;
c.Ws[i].XID = 0;
}
db.Entry<Content>(c).State = System.Data.EntityState.Added;
db.SaveChanges();
}
}
Or Is there other way of making copy of entity objects.
NOTE: there are multiple properties in each W,X,Y,Z.
In entity-framework-5, this is insanely easy with the DbExtensions.AsNotracking().
Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext.
This appears to be the case for all objects in the object graph.
You just have to really understand your graph and what you do and don't want inserted/duplicated into the DB.
Lets assume we have objects like:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int ID { get; set; }
public AddressLine { get; set; }
public int StateID { get; set; }
public ICollection<State> { get; set; }
}
So in order to Duplicate a person, I need to duplicate the addresses, but I don't want to duplicate the States.
var person = this._context.Persons
.Include(i => i.Addresses)
.AsNoTracking()
.First();
// if this is a Guid, just do Guid.NewGuid();
// setting IDs to zero(0) assume the database is using an Identity Column
person.ID = 0;
foreach (var address in person.Addresses)
{
address.ID = 0;
}
this._context.Persons.Add(person);
this._context.SaveChanges();
If you then wanted to then reuse those same objects again to insert a third duplicate, you'd either run the query again (with AsNoTracking()) or detach the objects (example):
dbContext.Entry(person).State = EntityState.Detached;
person.ID = 0;
foreach (var address in person.Addresses)
{
dbContext.Entry(address).State = EntityState.Detached;
address.ID = 0;
}
this._context.Persons.Add(person);
this._context.SaveChanges();
You need to make correct deep copy of the whole entity graph - the best way is to serialize the original entity graph to memory stream and deserialize it to a new instance. Your entity must be serializable. It is often used with DataContractSerializer but you can use binary serialization as well.
C is not a copy it is the record, the error you are getting is because you are trying to update it's primary key, even if you weren't it still wouldn't work. You need to make a new X entity and then copy the values from the properties of the retrieved entity and then insert the new entity.
Not sure if it works in 4.1, from http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4:
public static T CopyEntity<T>(MyContext ctx, T entity, bool copyKeys = false) where T : EntityObject
{
T clone = ctx.CreateObject<T>();
PropertyInfo[] pis = entity.GetType().GetProperties();
foreach (PropertyInfo pi in pis)
{
EdmScalarPropertyAttribute[] attrs = (EdmScalarPropertyAttribute[])pi.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false);
foreach (EdmScalarPropertyAttribute attr in attrs)
{
if (!copyKeys && attr.EntityKeyProperty)
continue;
pi.SetValue(clone, pi.GetValue(entity, null), null);
}
}
return clone;
}
You can copy related entites to your cloned object now too; say you had an entity: Customer, which had the Navigation Property: Orders. You could then copy the Customer and their Orders using the above method by:
Customer newCustomer = CopyEntity(myObjectContext, myCustomer, false);
foreach(Order order in myCustomer.Orders)
{
Order newOrder = CopyEntity(myObjectContext, order, true);
newCustomer.Orders.Add(newOrder);
}
I use Newtonsoft.Json, and this awesome function.
private static T CloneJson<T>(T source)
{
return ReferenceEquals(source, null) ? default(T) : JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source));
}

Categories

Resources