Code First Empty Navigation Property - c#

I have a really weird issue going on that I can't seem to find the answer on google for.
I currently have the following Code First/DB structure:
public class Prospect {
[Key]
public int ProspectId { get; set; }
public int ProspectCompanyId { get; set; }
public int? ImportUserId { get; set; }
public int? ProspectUserId { get; set; }
public int? SalesUserId { get; set; }
public int? CampaignId { get; set; }
[ForeignKey("CampaignId")]
public virtual ICollection<CampaignEvent> CampaignEvents { get; set; }
[ForeignKey("CampaignId")]
public virtual Campaign Campaign { get; set; }
}
public class CampaignEvent
{
[Key]
public int CampaignEventId { get; set; }
public int CampaignId { get; set; }
public int UserId { get; set; }
public string ActionType { get; set; }
public string ActionSubject { get; set; }
public string ActionTemplate { get; set; }
}
The problem is that when I try to return a query like:
var prospects = db.Prospects.Include("CampaignEvents");
The prospects.First().CampaignEvents is empty - when it should be populated with records.
I've even taken the SQL generated by the Entity Framework and executed it with it successfully returning the prospect and campagin events directly in the database.
I'm at a loss of what to do - its very odd, I receive no errors, just an empty collection.
Please let me know if you need any additional details!

try with
var prospects = db.Prospects.Include("CampaignEvents");
var value = prospects.FirstOrDefault(p=>p.CampaignEvents.Any());

Related

Code First Entity Framework - Column returns null becuase EF changed the name to include _ID

Entity framework changed the column name in the DB, and isn't giving me it's value.
Here are my classes:
public class Settings
{
[Key]
public int ID { get; set; }
public string Setting { get; set; }
public string MoreDetail { get; set; }
public SettingTypes Type { get; set; }
public SettingGroups SettingGroup { get; set; }
public int? MinMembership { get; set; }
public string DefaultValue { get; set; }
public int? ParentID { get; set; }
public int Order { get; set; }
}
public class SettingTypes
{
[Key]
public int ID { get; set; }
[MaxLength(35)]
public string TypeName { get; set; }
}
public class SettingGroups
{
[Key]
public int ID { get; set; }
[MaxLength(35)]
public string GroupName { get; set; }
}
In the DB you can see that it changed the name of the two columns:
When I try to loop through the results, type is null:
How do I retrieve this value? I've tried renaming the columns in the class and in the DB but that just breaks more things. What's the proper way to handle this?
Thanks!
Dangit, I figured it out. Spent way to much time doing so.
It was as simple as adding "virtual" to the properties:
public virtual SettingTypes Type { get; set; }
public virtual SettingGroups SettingGroup { get; set; }
Now I can address it like:
setting.Type.TypeName
Hope this saves someone else some time.

How to define a navigation property via Entity Framework code first approach

I have the following class that I want to use as my data context in Entity Framework:
public class AggregateRecord : IAggregateRecord
{
[Key]
public int AggregateRecordID { get; set; }
public DateTime? InsertDate { get; set; } = DateTime.Now;
public DateTime BookingDate { get; set; }
public string AmountTypeName { get; set; }
public int? UnifiedInstrumentCode { get; set; }
public double? Amount { get; set; }
public string BookingAccountID { get; set; }
public string AccountCurrency { get; set; }
public string ClientCurrency { get; set; }
public string AffectsBalance { get; set; }
public string AssetType { get; set; }
public string UnderlyingInstrumentSubType { get; set; }
public string InstrumentSymbol { get; set; }
public string InstrumentSubType { get; set; }
public string UnderlyingInstrumentAssetType { get; set; }
public string UnderlyingInstrumentDescription { get; set; }
public string UnderlyingInstrumentSymbol { get; set; }
public string UnderlyingInstrumentUic { get; set; }
public double? AmountAccountCurrency { get; set; }
public string AmountClientCurrency { get; set; }
public string InstrumentDescription { get; set; }
public virtual ICollection<InstrumentInfo> InstrumentInfo { get; set; }
}
public class InstrumentInfo
{
[Key]
public int InstumentInfoID {get;set;}
public string SomeInformation { get; set; }
public int AggregateRecordID { get; set; }
public virtual AggregateRecord AggregateRecord { get; set; }
}
I have studies the examples provided for EF6 but I still have the problem that when I try to update my migration that I get the following error:
One or more validation errors were detected during model generation:
There are no primary or candidate keys in the referenced table 'dbo.AggregateRecords' that match the referencing column list in the foreign key 'FK_dbo.InstrumentInfoes_dbo.AggregateRecords_AggregateRecordID'.
Could not create constraint or index. See previous errors.
How do I have to define the classes so that InstrumentInfo can be accessed via a navigation property?
public class InstrumentInfo
{
[Key]
public int InstumentInfoID {get;set;}
public string SomeInformation { get; set; }
public int AggregateRecordId { get; set; }
public virtual AggregateRecord AggregateRecord { get; set; }
}
Seems you forgot "public"
I "solved" the problem. It's weird, but maybe it helps somebody in future that's why I answer my own question.
I renamed my class AggregateRecord to AggregateEntry. Performed the Add-Migration and Update-Database, with the new renamed class name. And it worked.
It looks like there was some problem with the migration definition or whatsoever, but it solved it.
In the end, I renamed it back to the original name, did the same procedure again and, voila, it works.
#Dennis Spade: Thanks for your effort, without your hint it would have taken me even more time to find the real "problem".

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

Linq update with an Ilist

I would like to update my database datas and I have the following 2 "lists" of element :
Linq Query returning me an IQueryable<VM_CategoryLabel> from the database (that has to be updated)
IList<VM_CategoryLabelExtra> (list coming from a web interface)
Here are my 2 classes:
public class VM_CategoryLabel
{
public int Id { get; set; }
public int Order { get; set; }
public string Label { get; set; }
public string Unit { get; set; }
public bool Checked { get; set; }
}
public class VM_CategoryLabelExtra
{
public int Id { get; set; }
public int IdCat { get; set; }
public int Order { get; set; }
public string Label { get; set; }
public string Unit { get; set; }
public bool Checked { get; set; }
}
It seems so basic, but I get an error and was unsuccessful trying with Linq to join or with the let. Maybe the way I am doing it is totally wrong ?

Categories

Resources