Large data object - am I worrying too much - c#

I work with EF for the first time so I don't know is situation like this normal or I have serious performance issues.
I have following situation:
Bellow are the classes that I have. Item is the main object here. So when I pull a list of Items from database I get for example 1000 items. And now each of this item has all properties filed with data. City contains Country, Country contains list of cities, User has list of created items, each item all data again, city, city has country, country list of cities etc etc...
Maybe I am worrying too much and I don't know should this object's contain all those data and does this make performance issues, or I am doing something wrong here?
public abstract class Item
{
[Key]
public int ItemId { get; set; }
public int ItemTypeId { get; set; }
public Guid UserId { get; set; }
public DateTime CreatedOnDate { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int? MediaId { get; set; }
public int CityId { get; set; }
public virtual City City { get; set; }
public virtual User User { get; set; }
public virtual ICollection<ItemInBoard> ItemsInBoard { get; set; }
public virtual ICollection<Like> Likes { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class City
{
public int CityId { get; set; }
public string Name { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
public int CountryId { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
public class User
{
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Gender { get; set; }
public DateTime? BirthDay { get; set; }
public string AboutMe { get; set; }
public int? MediaId { get; set; }
public int CityId { get; set; }
public virtual City City { get; set; }
public virtual ICollection<Item> Items { get; set; }
public virtual ICollection<Board> Boards { get; set; }
public virtual ICollection<Like> Likes { get; set; }
}

It is up to you. This is a concept called lazy loading. You can enable or disable lazy loading with this code:
context.Configuration.LazyLoadingEnabled = false;
context.Configuration.LazyLoadingEnabled = true;
When enabling this option none of the dependent entities will be loaded. To enforce dependent entities to load you can use the Include lambada expression like this:
var test = context.Tests.Include("SomeOtherDependentEntity");
Hope I got you and this is what you meant.

I would say that what you have is fine for general business logic.
When I have to do a lot of time sensitive processing in a read-only fashion I use SQL commands like this to get exactly and only exactly what I want.
public class myQueryClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
var context = new MyDbContext();
context.Database.SqlQuery<myQueryClass>("SELECT Property1 = acolumn, Property2 = acolumn2 FROM myTable WHERE something = somestate");

Related

ServiceStack OrmLite mapping with references not working

I'm trying out OrmLite to see if I can replace Entity Framework in my projects. The speed is quite significant on simple queries. But I tried to map/reference a [1 to many- relation and read the documentation + examined the test code from the github page but without success. This is my example. Is there something I've forgot or should do to get it working like Entity Framework?
Example
// EF: returns +15.000 records + mapped > product.StockItems (slow)
dbContext.Products.Include(x => x.StockItems).ToList();
// OrmLite: returns +100.000 records (NO mapping > product.StockItems)
db.Select<Product>(db.From<Product>().Join<StockItem>());
// OrmLite: +15.000 separate requests to sql server (bad workarround + slow)
foreach (var product in db.Select<Product>())
{
// manual mapping
product.StockItems = db.Select<StockItem>(x => x.ProductId == product.Id);
}
Product.cs
public class Product
{
public int Id { get; set; }
public ProductType ProductType { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal SpecialPrice { get; set; }
public decimal DiscountPercentage { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
//...
[Reference]
public virtual IList<StockItem> StockItems { get; set; } = new List<StockItem>();
}
StockItem.cs
public class StockItem
{
public int Id {get; set;}
[References(typeof(Product))]
public int ProductId { get; set; }
public string Size { get; set; }
public int TotalStockQuantity { get; set; }
public string Gtin { get; set; }
public int DisplayOrder { get; set; }
// ...
[Reference]
public virtual Product Product { get; set; }
}
Ideally your POCOs/DTOs shouldn't use interfaces and you don't need to use virtual as ORM only populates your own POCOs (i.e. it doesn't create proxies of your models like other Heavy ORMs), I also prefer to use [AutoIncrement] for integer Ids (unless you need to populate specific Ids) so my Models would look like:
public class Product
{
[AutoIncrement]
public int Id { get; set; }
public ProductType ProductType { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal SpecialPrice { get; set; }
public decimal DiscountPercentage { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
[Reference]
public List<StockItem> StockItems { get; set; }
}
public class StockItem
{
[AutoIncrement]
public int Id { get; set; }
[References(typeof(Product))]
public int ProductId { get; set; }
public string Size { get; set; }
public int TotalStockQuantity { get; set; }
public string Gtin { get; set; }
public int DisplayOrder { get; set; }
}
OrmLite's POCO References only populate 1-level deep and it's not a good idea to have cyclical relationships as they're not serializable so I'd remove the back reference on StockItems as it's not going to be populated.
You also need to use LoadSelect in order to query and return POCOs with references, so to return Product with their StockItem references you can just do:
db.LoadSelect<Product>();
You can also populate this manually with 2 queries by using Merge extension method to merge 2 disconnected record sets, e.g:
var q = db.From<Product>().Join<StockItem>();
var products = db.Select(q.SelectDistinct());
var stockItems = db.Select<StockItem>();
products.Merge(stockItems);
Which will merge Products with their StockItems which you can quickly see by running:
products.PrintDump();

Save complexa data using entity framework

Hi every one I want to save complex data using Entity Framework and C#. I have 2 classes Product and Order defined as follows
Product Class
public class Product
{
[Key]
public int Id { get; set; }
public string SKU_Code { get; set; }
public string Product_Name { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public string Image { get; set; }
public DateTime Created_Date { get; set; }
public DateTime Modified_Date { get; set; }
}
Order Class
public class Order
{
[Key]
public long ID { get; set; }
public string Order_Id { get; set; }
public string Payment_Type { get; set; }
public string Customer_Name { get; set; }
public string Shipping_Address { get; set; }
public DateTime Order_Date { get; set; }
public DateTime Modified_Date { get; set; }
public bool Flag { get; set; }
public List<Product> ProductDetails { get; set; }
}
And I want to save data Order details and my piece of code is as follows.
public Order Add(Order odrerDetails)
{
using (var context = new EcommerceDBContext())
{
var MyOrder_Id = Helper.Random(7); //Generate random orderID from my class
foreach (var detail in odrerDetails.ProductDetails)
{
odrerDetails.Order_Id = MyOrder_Id;
odrerDetails.Quantity = Convert.ToInt32(detail.Quantity);
odrerDetails.Amount = Convert.ToDouble(detail.Price);
//Other Details
context.objOrderListing.Add(odrerDetails);
}
context.SaveChanges();
return odrerDetails;
}
}
This gives me perfect data but when it comes to context.SaveChanges(); it return's me error.
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.
To me you domain model seems all wrong. The order should just be used for grouping, its a typical e-commerce scenario.
When you get a receipt of your purchases, you get one receipt with every Item and price listed next to it. Its considered as one order of multiple things, not multiple orders of multiple things.
Reading your last comment, you cant have multiple orders with the same order id. Try to understand the domain first before trying to solve it with code. Also,you have no notion of a Customer with an Order.
public class Product
{
[Key]
public int Id { get; set; }
public string SKU_Code { get; set; }
public string Product_Name { get; set; }
public string Price { get; set; }
public string Image { get; set; }
public DateTime Created_Date { get; set; }
public DateTime Modified_Date { get; set; }
}
public class Order
{
[Key]
public long ID { get; set; }
public string Order_Id { get; set; }
public string Payment_Type { get; set; }
public string Customer_Name { get; set; }
public string Shipping_Address { get; set; }
public DateTime Order_Date { get; set; }
public DateTime Modified_Date { get; set; }
public bool Flag { get; set; }
public List<OrderLineItem> Items { get; set; }
}
public class OrderLineItem
{
[Key]
public long ID { get; set; }
public long Order_Id { get; set; }
public long Product_Id {get; set;}
public int Quantity {get; set;}
}

c# lambda query to load item in a related table

Lambda Query
I am working with with EF6 MVC5 and set up my listing model to include a virtual ICollection of images. I want to query the listings and include an image with each listing title in my view. I am having trouble writing the lambda query in the controller to send to my view.
Listing Class
public class Listing
{
public int Id { get; set; }
public ApplicationUser User;
[Required]
public string UserId { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string Phone { get; set; }
public string LocationAddress1 { get; set; }
public string LocationAddress2 { get; set; }
public string LocationCity { get; set; }
public string LocationState { get; set; }
public string LocationZip { get; set; }
public string LocationCountry { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
[DataType(DataType.MultilineText)]
public string Comments { get; set; }
public bool isLEO { get; set; }
public bool isProperty { get; set; }
public string Keywords { get; set; }
public bool isNoShowAddress { get; set; }
public bool isActive { get; set; }
public bool isApproved { get; set; }
public virtual ICollection<Image> Images { get; set; }
public virtual ICollection<Review> Reviews { get; set; }
Image Class
public class Image
{
public int Id { get; set; }
public Listing Listing { get; set; }
public int ListingId { get; set; }
public string ImagePath { get; set; }
public bool isPrimary { get; set; }
public DateTime DateAdded { get; set; }
public bool isHidden { get; set; }
}
When you have nested objects I believe you do something like this:
var listings = dbcontext.Listings.Include("Images").Where(...)
Where include tells EF to fetch nested objects.
It could also be something like this:
var listings = dbcontext.Listings.Include(c=>c.Images).Where(...)
You have to project your query to another type specifically designed for use inside Views (this is often referred to as ViewModel) or you can just project it into an anonymous type, the approach is similar.
The following code assumes you will use an anonymous type:
var listings = dbContext.Listings.Select(l => new {
Id = l.Id,
User = l.User,
//add every property you need to show inside your View
Image = l.Images.FirstOrDefault(i => i.isPrimary)
});

Combining Entities into ViewModels and using Entity Framework

Most tutorials don't really cover this at all. They just say link your entity to a controller and you're done.
In my business model I have Customers and I have Customer Contacts 1 Customer to >1 Customer Contacts. How do I create a view model for these that will allow them to be edited/created/whatever from the same view?
public class Customer
{
public Customer()
{
this.CustomerContacts = new List<CustomerContact>();
this.Systems = new List<System>();
this.CreatedByCustomerTickets = new List<Ticket>();
this.CustomerTickets = new List<Ticket>();
}
public long CustomerID { get; set; }
public Nullable<bool> BusinessCustomer { get; set; }
public string CustomerName { get; set; }
public string CustomerNotes { get; set; }
public virtual ICollection<CustomerContact> CustomerContacts { get; set; }
public virtual ICollection<System> Systems { get; set; }
public virtual ICollection<Ticket> CreatedByCustomerTickets { get; set; }
public virtual ICollection<Ticket> CustomerTickets { get; set; }
}
public class CustomerContact
{
public long CustomerContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Phone { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public Nullable<int> Zip { get; set; }
public Nullable<long> CustomerID { get; set; }
public string Email { get; set; }
public bool PromotionalEmails { get; set; }
public virtual Customer Customer { get; set; }
}
Well I'd start with this
public class CustomerViewModel
{
public Customer Customer {get; set;}
public CustomerContact CustomerContact {get; set;}
}
and work from there.
If you don't need all the properties from the domain objects, you may consider something more like:
public class CustomerViewModel
{
public long CustomerID { get; set; }
public ICollection<CustomerContact> CustomerContacts { get; set; }
}
It's really up to you to construct your view models in a way that will meet the needs of your specific project.

EF4.1 Code First Question

I want to create my first application using the EF 4.1 Code First Model. I want to model a magazine subscription but just want to check that my POCO classes are fit for purpose.
The following are my classes. Am I missing anything?
Should Customer be a member of Subscription or should it be just that List be a member of Customer?
Thanks.
public class Subscription
{
public int SubscriptionID { get; set; }
public string CardNumber { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public decimal NetPrice { get; set; }
public decimal Tax { get; set; }
public decimal Discount { get; set; }
public string PromotionalCode { get; set; }
public Customer Customer{ get; set; }
}
public class Customer {
public int CustomerID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public PostalAddress PostalAddress { get; set; }
public string EmailAddress { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public DateTime DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public bool Valid { get; set; }
public IList<Subscription> Subscriptions { get; set; }
public bool MailMarketing { get; set; }
public bool PartnerMailMarketing { get; set; }
}
public class PostalAddress
{
public int ID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
public string Region { get; set; }
public string Country { get; set; }
}
If a Customer have X suscriptions, every suscription should have the customerID so you need that in your Suscription class (public int CustomerID {get; set;}).
OTOH, I think that you have to put that Customer reference as virtual and the suscription one (I don't know why).
Maybe Im wrong but that works for me.
Anyway, what's your problem?
Your models look correct. You don't necessarily need the Customer property in the Subscription class, but it does help if you want to retrieve a specific Subscription and then want to find the customer that is tied to that subscription. In that instance you can then do var customer = mySub.Customer instead of querying for a customer with the specific subscription id.

Categories

Resources