How to Map Sql Query to EF Models when using FromSql - sql-server

I am trying to use .FromSql but I keep getting an exception
"Required Column Id is Missing"
Now all my Models have Id so I have no clue which one I am missing, or if I am writing my "As" statements wrong and it is not mapping properly.
var inventoryItems = dbContext.InventoryItems.AsNoTracking().FromSql(#"SELECT Brands.Id AS BrandsId, InventoryItems.Id AS InventoryItemsId,
Companies.Id AS CompaniesIds, Countries.Id AS CountriesId, States.Id AS StatesId, Branches.Id AS BranchesId,
Branches.CountryId, Branches.StateId, States.CountryId AS StatesCountryId, InventoryItems.InventoryCategoryId, InventoryItems.BrandId, InventoryItems.BranchId, Branches.CompanyId
FROM Branches INNER JOIN
Brands ON Branches.Id = Brands.Id INNER JOIN
Companies ON Branches.CompanyId = Companies.Id INNER JOIN
Countries ON Branches.CountryId = Countries.Id INNER JOIN
InventoryItems ON Branches.Id = InventoryItems.BranchId AND Brands.Id = InventoryItems.BrandId INNER JOIN
States ON Branches.StateId = States.Id AND Countries.Id = States.CountryId ).ToList();
Model example and all my models follow the same pattern
public class InventoryItem
{
public int Id { get; set; } //PK name
public int InventoryCategoryId { get; set; } // FK name pattern
public int BranchId { get; set; }
public virtual Branch Branch { get; set; }
public int BrandId { get; set; }
public virtual Brand Brand { get; set; }
}
I am using FromSql because I need to do a where clause(not shown) that filters on a json column with EF core does not support.

a .FromSql query returns a single Entity Type. That query should return Id, InventoryCategoryId, BranchId, BrandId, one column for each property of Inventory Item (except for Navigation Properties).
If you want to load multiple different entity types, you can't use a single .FromSql() call. Instead use one of the methods detailed here. Especially note:
Entity Framework Core will automatically fix-up navigation properties
to any other entities that were previously loaded into the context
instance. So even if you don't explicitly include the data for a
navigation property, the property may still be populated if some or
all of the related entities were previously loaded.
So you can fetch the Entities you need across multiple seperate queries if you want. But this "fix-up" doesn't happen if you suppress change tracking on your Entities, as it's the change tracker that does this.

Related

Why am I getting DbUpdateException: OptimisticConcurrencyException?

I have a Category class:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
I also have a Subcategory class:
public class Subcategory
{
public int SubcategoryId { get; set; }
public Category Category { get; set; }
public string SubcategoryName { get; set; }
}
And a Flavor class:
public class Flavor
{
public int FlavorId { get; set; }
public Subcategory Subcategory { get; set; }
public string FlavorName { get; set; }
}
Then I also have Filling and Frosting classes just like the Flavor class that also have Category and Subcategory navigation properties.
I have a Product class that has a Flavor navigation property.
An OrderItem class represents each row in an order:
public class OrderItem
{
public int OrderItemId { get; set; }
public string OrderNo { get; set; }
public Product Product { get; set; }
public Frosting Frosting { get; set; }
public Filling Filling { get; set; }
public int Quantity { get; set; }
}
I'm having issues when trying to save an OrderItem object. I keep getting DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. with the Inner Exception being OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. I've stepped through my code several times and I can't find anything that modifies or deletes any entities loaded from the database. I've been able to save the OrderItem, but it creates duplicate entries of Product, Flavor, Subcategory and Category items in the DB. I changed the EntityState of the OrderItem to Modified, but that throws the above exception. I thought it might have been the fact that I have Product, Frosting and Filling objects all referencing the same Subcategory and Category objects, so I tried Detaching Frosting and Filling, saving, attaching, changing OrderItem entity state to Modified and saving again, but that also throws the above exception.
The following statement creates duplicates in the database:
db.OrderItems.Add(orderItem);
Adding any of the following statements after the above line all cause db.SaveChanges(); to throw the mentioned exception (both Modified and Detached states):
db.Entry(item).State = EntityState.Modified;
db.Entry(item.Product.Flavor.Subcategory.Category).State = EntityState.Modified;
db.Entry(item.Product.Flavor.Subcategory).State = EntityState.Modified;
db.Entry(item.Product.Flavor).State = EntityState.Modified;
db.Entry(item.Product).State = EntityState.Modified;
Can someone please give me some insight? Are my classes badly designed?
The first thing to check would be how the entity relationships are mapped. Generally the navigation properties should be marked as virtual to ensure EF can proxy them. One other optimization is that if the entities reference SubCategory then since SubCats reference a Category, those entities do not need both. You would only need both if sub categories are optional. Having both won't necessarily cause issues, but it can lead to scenarios where a Frosting's Category does not match the category of the Frosting's SubCategory. (Seen more than enough bugs like this depending on whether the code went frosting.CategoryId vs. frosting.SubCategory.CategoryId) Your Flavor definition seemed to only use SubCategory which is good, just something to be cautious of.
The error detail seems to point at EF knowing about the entities but not being told about their relationships. You'll want to ensure that you have mapping details to tell EF about how Frosting and SubCategory are related. EF can deduce some of these automatically but my preference is always to be explicit. (I hate surprises!)
public class FrostingConfiguration : EntityTypeConfiguration<Frosting>
{
public FlavorConfiguration()
{
ToTable("Flavors");
HasKey(x => x.FlavorId)
.Property(x => x.FlavorId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(x => x.SubCategory)
.WithMany()
.Map(x => x.MapKey("SubCategoryId");
}
}
Given your Flavor entity didn't appear to have a property for the SubCategoryId, it helps to tell EF about it. EF may be able to deduce this, but with IDs and the automatic naming conventions it looks for, I don't bother trying to remember what works automagically.
Now if this is EF Core, you can replace the .Map() statement with:
.ForeignKey("SubCategoryId");
which will set up a shadow property for the FK.
If SubCats are optional, then replace HasRequired with HasOptional. The WithMany() just denotes that while a Flavor references a sub category, SubCategory does not maintain a list of flavours.
The next point of caution is passing entities outside of the scope of the DBContext that they were loaded. While EF does support detaching entities from one context and reattaching them to another, I would argue that this practice is almost always far more trouble than it is worth. Mapping entities to POCO ViewModels/DTOs, then loading them on demand again when performing updates is simpler, and less error-prone then attempting to reattach them. Data state may have changed between the time they were initially loaded and when you go to re-attach them, so fail-safe code needs to handle that scenario anyways. It also saves the hassle of messing around with modified state in the entity sets. While it may seem efficient to not load the entities a second time, by adopting view models you can optimize reads far more efficiently by only pulling back and transporting the meaningful data rather than entire entity graphs. (Systems generally read far more than they update) Even for update-heavy operations you can utilize bounded contexts to represent large tables as smaller, simple entities to load and update a few key fields more efficiently.

How do I use a composite key for a one to many relationship in Code First EF

I am using EF Code First.
I need two tables, LedgerCategories and LedgerSubCategories with a one-to-many relationship (Categories -> SubCategories), with the keys in each being codes (strings) - i.e. LedgerCategoryCode and LedgerSubCategoryCode respectively. However, I need to allow the SubCategoryCode values to be the same for different Categories.
E.g. CategoryCode = REHAB, SubCategoryCodes = MATL, CONTR, and FEES; and CategoryCode = MAINT, SubCategoryCodes = MATL, CONTR, and FEES.
I'm thinking I need to use a composite key and include both the CategoryCode and SubCategoryCode fields in the LedgerSubCategories table. Currently I have:
public class LedgerCategory
{
[Key]
public string LedgerCategoryCode { get; set; }
public string Description { get; set; }
public List<LedgerSubCategory> LedgerSubCategories { get; set; }
}
public class LedgerSubCategory
{
[Key, Column(Order = 0)]
public string LedgerCategoryCode { get; set; }
[Key, Column(Order = 1)]
public string LedgerSubCategoryCode { get; set; }
public string Description { get; set; }
}
I am seeding these tables using only instances of the LedgerCategory class, having each contain a List of appropriately instantiated LedgerSubCategory classes. This appears to both set up the DB schema correctly (in my perception), and populate both tables appropriately.
But, when I reinstantiate a simple List of LedgerCategory, i.e.
using (var db = new BusinessLedgerDBContext())
{
var LedgerCategories = db.LedgerCategories.ToList();
}
The LedgerCategory instances don't contain their respective List of associated LedgerSubCategory instances.
I am trying to avoid, what seems like a kludge, to introduce a unique number or Guid ID field in LedgerSubCategories as a PK and just index off the other Code fields. I haven't tried this, but I'm not sure it would cause any different results for reinstantiating the LedgerCategories and getting associated LedgerSubCategories.
Any advice on how to do this appropriately and get proper results is appreciated.
To, I suppose, answer my own question, I have found that overriding OnModelCreating() in the respective DbContext with Fluent API to establish the one to many relationship and foreign key when the Code First framework establishes the desired DB Schema. There appears no other way to do this, such as with Attributes. By many accounts of others, including MSDN, Fluent API appears to be what is needed. However, that has led me to a new issue, or set of issues, which I've posed as a question here.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Configures the one-many relationship between Categories and
// SubCategories, and established the Foreign Key in SubCategories
modelBuilder.Entity<Category>()
.HasMany<SubCategory>(c => c.SubCategories)
.WithRequired(s => s.Category)
.HasForeignKey<string>(s => s.CategoryCode);
}

Map List object using SQL Server and Dapper

I'm using SQL Server and Dapper and I want to properly store my models object into database and retrieve them.
That's my model, the guid list is list of other model 'Generator' IDs.
public class GeneratorSet
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Guid> GeneratorsList { get; set; }
}
My goal is to correctly map this object to a SQL Server table and then using Dapper correctly retrieve my objects from database. The relationship is many to many (set can 'posses' many generators, and generator may be possesed by many sets).
You can do this using the SplitOn parameter... Here is a guide;
https://taylorhutchison.github.io/2016/03/23/dapper-orm-complex-queries.html
Or just by having unique names and mapping using a lambda - using the example from the documentation (https://github.com/StackExchange/Dapper);
var sql =
#"select * from #Posts p
left join #Users u on u.Id = p.OwnerId
Order by p.Id";
var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});
var post = data.First();
Assert.Equal("Sams Post1", post.Content);
Assert.Equal(1, post.Id);
Assert.Equal("Sam", post.Owner.Name);
Assert.Equal(99, post.Owner.Id);
I can't write the actual code/query as I don't know your database schema... but hopefully you get the idea?

Passing computed values with RIA Services

I'm trying to figure out the a way to get extra data to be passed with the entities returned from a RIA domain service.
For example, let's say I want to display a DataGrid for "Orders" and include a column for the total items in an order.
Order Num. | Cust. Name | *No. of Items Ordered*
4545 | John | 4
1234 | Mike | 7
On the server side, with a Linq query, I could do:
var query =
from o in entities.Orders
select new OrderWithItemCount { Order = o, ItemCount = o.Items.Count() };
... and this will retrieve my orders along with the Items counts all in one go.
The problem is, I can't find anyway to propagate these results thru a domain service to the Silverlight client. I suppose I could use a standard WCF service, but what's the fun in that?
Update
What turned out to be the actual problem...
I had at one point actually already tried the "Easy way" that Nissan Fan and Florian Lim point out. When I tried it, I wasn't getting all my data. (I also need to include the customer Person in the query to get their name.) It turns out that what I thought was a limitation of RIA Services was actually a limitation of EF 4.0, in that saying entities.Orders.Include("Customer") won't work if you select a new type that isn't an Order. The work around is to explicitly select o.Customer in your select statement, and EF will automatically wire the selected Person into the assiocated property on Order.
Easy way:
Just add extra fields to your Order class (could be done in a partial class) and populate that in your DomainService.
Complicated but more flexible way:
Define OrderWithItemCount as an entity (needs to have a [Key] attribute), then transfer that.
public class OrderWithItemCount
{
[Key]
public int Id { get; set; }
// You need this, so that the DomainContext on the client can put them back together.
public int OrderId { get; set; }
[Include]
[Association("OrderReference", "OrderId", "Id")]
public Order Order { get; set; }
public int ItemCount { get; set; }
public Person Customer { get; set; }
}
public IQueryable<OrderWithItemCount> GetOrdersWithItemCount()
{
var query = from o in entities.Orders
select new OrderWithItemCount
{
OrderId = o.Id,
Order = o,
ItemCount = o.Items.Count,
Customer = o.Customer, // Makes sure EF also includes the Customer association.
};
return query;
}
There may be minor errors in the code, since I cannot test this at the moment, but I recently implemented something similar.
If you are using LINQ to SQL to produce your Domain Service you could simply go into the partial class for Orders and add a Property called NumberOfOrders which returns an Int representing the count. This property would carry through to the client without issue.
internal sealed class OrderMetadata
{
// Metadata classes are not meant to be instantiated.
private OrderMetadata()
{
}
... (property stubs auto-generated)
}
public int NumberOfOrders
{
get { return this.Items.Count; }
}
The reason why you cannot do this the way you demonstrated above is because you cannot marshal across anything but conrete classes (anonyous classes are a no-go). By adding this property to the partial class it will effectively be part of its published signature.

Fetch Tags and Tag count using HQL on SQL Server 2008

I'm implementing tagging on a particular entity, using NHibernate on SQL Server 2008. The structure I have now is, simplifying, like this:
public class Entity {
public Guid Id { get; set; }
}
public class Tag {
public Guid Id { get; set; }
public string Name { get; set; }
}
public class TagAssoc {
public Tag LinkedTag { get; set; }
public Entity LinkedEntity { get; set; }
//User
//Other properties
}
Nothing exotic: an entity can be tagged multiple times with the same tag, since the association also includes data about the user that tagged the entity and other stuff.
Now, I'm trying to fetch a list of tags of a particular entity, with the counts of how many times the tag has been applied. Something like this in HQL:
select tass.LinkedTag, count(tass.LinkedTag)
from TagAssoc as tass left outer join tass.LinkedTag as t
group by tass.LinkedTag
This generates the following SQL query:
select tag1_.Id as Id0_, tag1_.Name as Name0_, tag1_.Id as x0_0_, count_big(tag1_.Id) as x1_0_
from BandTags tagassoc0_ left outer join Tags tag1_ on tagassoc0_.TagId=tag1_.Id
group by tag1_.Id
This looks correct, but won't work in SQL Server 2008, because the Name property of Tag is not included in a "group by" clause. To make it work, I have to manually adjust the group by clause in order to include all properties of the Tag class:
select tass.LinkedTag, count(tass.LinkedTag)
from TagAssoc as tass left outer join tass.LinkedTag as t
group by tass.LinkedTag.Id, tass.LinkedTag.Name
But this depends on the properties of the Tag class and therefore would have to be updated every time the class is changed.
Is there some other way to make the first HQL query work? Perhaps some HQL syntax that automatically makes the "group by" properties explicit?
Thanks
It doesn't appear that there is any way to make NHibernate determine the group by properties automatically. The documentation even seems to imply this in the example HQL they give for an aggregate function:
select cat, count( elements(cat.Kittens) )
from Eg.Cat cat group by cat.Id, cat.Weight, ...
There they also explicitly specify the properties of Cat.
If you want to dynamically build a query that does not need an update every time the class changes, I think you're stuck with Reflection and the Criteria interface.
ProjectionList list = Projections.ProjectionList();
foreach (PropertyInfo prop in typeof(Tag).GetProperties())
{
list.Add(Projections.GroupProperty(prop.Name));
}
list.Add(Projections.Property("LinkedTag"));
list.Add(Projections.Count("LinkedTag"));
session.CreateCriteria(typeof(TagAssoc)).SetProjection(list).List();
I haven't tried this so it may or may not work or might need some tweaking, but you get the idea. You might decide the Tag class won't change enough to be worth the trouble.

Resources