Query some properties on relation with NHibernate - c#

I have a mapped model with Nhibernate like this:
public class A
{
public virtual long Id { get; set; }
public virtual long Number { get; set; }
/* and other 20 properties... */
}
public class B
{
public virtual long Id { get; set; }
public virtual A ItemA { get; set; }
public virtual string Name { get; set; }
public virtual DateTime Date { get; set; }
}
I would like to create a query (queryover, linq, hql etc... anyway) to get a List<B> and fill ItemA property with just Id and Number properties because I need only this properties (I have lots of properties in A class and I will not use it on my results). Is there any way to do this or should I create a ViewModel? If I need to create a ViewModel, how can I do this with QueryOver?
Thank you!

Yes, you have to create a view model, like following:
public class BViewModel
{
public virtual long Id { get; set; }
public virtual AViewModel ItemA { get; set; }
public virtual string Name { get; set; }
public virtual DateTime Date { get; set; }
}
public class AViewModel
{
public virtual long Id { get; set; }
public virtual long Number { get; set; }
}
Now you oculd query it with linq like this:
var listOfB = session.Query<B>()
.Select(b => new BViewModel
{
Id = b.Id,
Name = b.Name,
Date = b.Date,
ItemA = new AViewModel
{
Id = b.ItemA.Id,
Number = b.ItemA.Number,
},
}).ToList();

using QueryOver, you can use JoinAlias to join A with B, and SelectList to retrieve only the properties that you want.
Then use TransformUsing to transform the result into whatever format you want.
Something along the lines of:
A aTemplate = null;
s.QueryOver<B>().
.JoinAlias(() => aTemplate)
.Where (/*whatever conditions*/)
.SelectList(list => list
.Select(() => aTemplate.Id)
.Select(() => aTemplate.Number)
.TransformUsing(Transformers.AliasToBeanTransformer)
.List<A/*or some DTO*/>();

Related

Why can't I get this model to map to this viewmodel?

I have this entity model for a recursively structured category tree:
public class ProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public ProductCategory ParentCategory { get; set; } //nav.prop to parent
public ICollection<ProductCategory> Children { get; set; } = new List<ProductCategory>();
public ICollection<ProductInCategory> ProductInCategory { get; set; }
public ICollection<FrontPageProduct> FrontPageProduct { get; set; } // Nav.prop. to front page product
// Recursive sorting:
public void RecursiveOrder()
{
Children = Children.OrderBy(o => o.SortOrder).ToList();
Children.ToList().ForEach(r => r.RecursiveOrder());
}
}
... and this, supposedly, matching ViewModel:
public class ViewModelProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public bool Checked { get; set; } // Used for assigning a product to multiple categories in Product/Edit
// Nav.props:
public ViewModelProductCategory ParentCategory { get; set; } // Nav.prop. to parent
public ICollection<ViewModelProductCategory> Children { get; set; } // Nav.prop. to children
public IEnumerable<ViewModelProduct> Products { get; set; } // Products in this category
public IEnumerable<ViewModelFrontPageProduct> FrontPageProducts { get; set; }
public string ProductCountInfo { get { return Products?.Count().ToString() ?? "0"; } }
}
When I try to populate the viewmodel, like this:
List<ProductCategory> DbM =
await _context.ProductCategories
.Include(c => c.Children)
.Where(x => x.ParentId == null)
.OrderBy(o => o.SortOrder)
.ToListAsync();
foreach (var item in DbM)
{
VMSelectCategories.Add(
new ViewModelProductCategory{
Id = item.Id,
Children = item.Children,
Title = item.Title
});
}
VisualStudio screams at me that it can't implicitly convert ProductCategory to ViewModelCategory. This happens at Children = item.Children.
Why isn't it working? Can't I have additional properties in the viewmodel that I use unrelated to the original entity model? Like Checked and ProductCountInfo?
In this line:
Children = item.Children,
Children is the ViewModelProductCategory.Children property, which is type ICollection<ViewModelProductCategory>, while item.Children is the ProductCategory.Children property, which is type ICollection<ProductCategory>. They are different types and neither inherits or implements the other so why would you expect to be able to assign an object of one type to a property of the other type? Would you expect this to work:
var list1 = new List<int> {1, 2, 3};
List<string> list2 = list1;
Of course not (I hope) because assigning a List<int> object to a List<string> variable would be silly. What you're trying to do is exactly the same. You need to provide some way to convert from one type to the other and then implement that in your code. An option for that might be like this:
Children = item.Children.Select(pc => MapToViewModel(pc)).ToList(),
where MapToViewModel is a method that you write to create a ViewModelProductCategory and populate its properties from a ProductCategory parameter.
You might also look at using something like AutoMapper.

Join 3 One to Many Tables in Entity Framework

i have 2 tables that each one has a one-to-many relation to the table between and the table between has ids of 2 other tables
dbo.Posts dbo.Posts_Categories dbo.Categories
-ID -ID -ID
-Title -PostID -Name
-CategoryID
result i expect is :
Title = post1 Categories = web,mobile,desktop
Title = post2 Categories = app,game
...
i know how to query this in sql using Stuff function and For Xml Path but i have no idea how do i do this in entity framework!
any suggestion or book for how to do works in this way might help!
Edit: EF classes added:
public class Post : ReportingBase {
public Post() { }
[Required, MaxLength(500)]
public string Title { get; set; }
[Required, MaxLength(500)]
public string Address { get; set; }
[Required]
public string Body { get; set; }
[Required, MaxLength(500)]
public string Tags { get; set; }
[Required]
public int Visit { get; set; }
public virtual ICollection<Post_Category> Posts_Categories { get; set; }
public virtual ICollection<Post_AttachedFile> Posts_AttachedFiles { get; set; }
[ForeignKey("Image")]
public virtual int? ImageID { get; set; }
public virtual Image Image { get; set; }
}
public class Post_Category {
public Post_Category() { }
[Key, Column(Order = 0)]
public int PostID { get; set; }
[Key, Column(Order = 1)]
public int CategoryID { get; set; }
public virtual Post Post { get; set; }
public virtual Category Category { get; set; }
}
public class Category : EntityBase {
public Category() { }
[Required, MaxLength(50)]
public string Name { get; set; }
[Required, MaxLength(150)]
public string Address { get; set; }
public int? ParentID { get; set; }
public virtual ICollection<Post_Category> Posts_Categories { get; set; }
}
thank you in advance
Edit : According to #IvanStoev answer i did following :
List<P> p = context.Posts.Select(post => new {
Title = post.Title,
Categories = post.Posts_Categories.Select(pc => pc.Category.Name).ToList()
}).ToList();
and created a class called P :
public class P {
public string Title { get; set; }
public List<string> Categories { get; set; }
}
but it doesn't work correctly and the problem is how to return the result.
In EF it's even easier than in SQL thanks to the concept of so called navigation properties. All you need to know is a basic LINQ query syntax and just follow them (navigate) to get the data needed. For instance:
var result = db.Posts
.Select(post => new
{
Title = post.Title,
Categories = post.Posts_Categories
.Select(pc => pc.Category.Name)
.ToList()
})
.ToList();
The result is a list of anonymous type having string Title property and List<string> Categories property containing the related category names.
You can use Linqpad (software) to get familiarize with the Linq query it builds lambda expression for you by connecting to the database and provides output too to cross verify.
The below one is the lambda expression for joining the tables you have mentioned.
p - Post
pc - post_categories
c - categories
Code:
Posts.Join(Post_Categories, p => p.ID, pc => pc.ID, ( p, pc) => new { p = p, pc = pc})
.Join(Categories, pcc => pcc.pc.CategoryID, c => c.ID, ( pcc, c) => new { pcc = pcc, c = c})
.Select(p.Title)
.Select(c.Name)
You should be using .Include() for any join in EF Core.
I've come up with this simple example: one person can have many dogs.
public class Person
{
public Guid Id { get; set; }
public ICollection<Dog> Dogs { get; set; } // One Person can have many Dogs
}
public class Dogs
{
public Guid Id { get; set; }
public Guid PersonId { get; set; }
}
Generate the migrations after creating the models. Not going over how to do that in this answer.
Here's how you use .Include() to join upon the two different tables:
public class PersonRepository : RepositoryBase
{
public IEnumerable<Person> FetchPeopleWithManyDogs()
{
return DatabaseContext.Person
.Include(x => x.Dogs)
.Where(x => x.Dogs.Count() > 1).ToList();
}
}

How to get specific columns with one to many relationship

I have 3 tables , one to many relationship.
I need to get only specific columns with SelectMany method.
I need to get only Categories.CategoryName and Comments.CommentDate of the selected News object.
Here is my code
News news = db.News.Include(w => w.Categories)
.Include(w => w.Comments).SingleOrDefault(n => n.NewsId == Id);
Here are my Entities:
News Entity:
public partial class News
{
public News()
{
this.Categories = new HashSet<Category>();
this.Comments = new HashSet<Comment>();
}
public int NewsId { get; set; }
public string NewsTitle { get; set; }
public string NewsBody { get; set; }
public System.DateTime NewsDate { get; set; }
public string NewsImagePath { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
Category Entity:
public partial class Category
{
public Category()
{
this.News = new HashSet<News>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<News> News { get; set; }
}
Comment Entity:
public partial class Comment
{
public Comment()
{
this.News = new HashSet<News>();
}
public int CommentId { get; set; }
public string CommentBody { get; set; }
public Nullable<System.DateTime> CommentDate { get; set; }
public virtual ICollection<News> News { get; set; }
}
This LINQ query should take care of it:
var query =
from news in db.News
where news.Id == Id
let categoryNames =
from category in news.Categories
select category.Name
let commentDates =
from comment in news.Comments
select comment.CommentDate
select new {
CategoryNames = categoryNames.ToList(),
CommentDates = commentDates.ToList()
};
That query is not using SelectMany, but that wouldn't help you, since then you wouldn't be able to group your categories and comments by news items. Since categories and comments are not directly connected, you'd need two SelectManys and then you'd need to cross join the results. That would obviously not be what you want.
Maybe try using the following?
var categoryNames = news.Categories.Select(c=>c.CategoryName);
var commentDates = news.Comments.Select(c=>c.CommentDate);
Note that SelectMany is used to flatten lists.For example, lets say you have collection of news matching certain search criteria, and then you use SelectMany to collect all the Categories/Comments of these news set, in a flat list.

How to join tables using LINQ to Entities query?

I have a simple db structure:
public class Person
{
[Key]
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Transport
{
[Key]
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
}
public class Accident
{
[Key]
public int AccsidentID { get; set; }
public DateTime AccidentDate { get; set; }
public int TransportID { get; set; }
[ForeignKey("TransportID")]
public virtual Transport Transport { get; set; }
public int PersonID { get; set; }
[ForeignKey("PersonID")]
public virtual Person Person { get; set; }
}
I need to create a list of accidents, wich I could pass to WPF form (using MVVM)
First I created new class witch I would like to see in my GridControl
public class AccsidentObject
{
[Key]
public int AccidentID { get; set; }
public DateTime AccidentDate { get; set; }
public int TransportID { get; set; }
public string Model { get; set; }
public string Brand { get; set; }
public int PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Could you please give me examples:
if I want to get list of all values from Accident table including data from Transport and Person tables
if I want to get Accident list grouped by TransportID (also include data from Person and Transport tables)
I am getting data from Linq query:
var result = from ac in DBContext.Accidents select ac;
List<Accident> accidentList = result.toList();
But I need to add some fields to list from other tables, what would be a code?
What do I do wrong and could not construct a list of AccidentObject, maybe there are some mistake in my DBContext, lists o something... Could you please help me to understand List elements??
Considering to 2 part I wrote:
var result = from ac in DBContext.Accidents select ac;
result = result.GroupBy(g => g.TransportID).toList();
And now I need to add some Transport details and format AccsidentObject list ...
To get an entity (or collection of entities) with associations eagerly populated use the Include extension method, or include in a final projection into your type:
var res = await (from a in ctx.Accidents
select new AccsidentObject {
AccidentID = a.AccidentID,
TransportID = a.Transport.TransportID,
Model = a.Transport.Model,
// …
}).ToListAsync();
You can use groupby in a LINQ comprehension expression to group by something. In the result the Key property is the thing grouped by and each instance is a collection of all things grouped by.
var res = await (from a in ctx.Accidents
group by a.TransportID into g
select new {
TransportID = g.Key,
Accidents = g
}).ToListAsync();
In the resulting anonymous types the Accidents property with be a collection of Accident.
var accidents = DBContext.Accidents.Select( a => new AccidentObject
{
AccidentID = a.AccidentId,
AccidentDate
TransportID
Model
Brand = a.Transport.Brand,
PersonID = a.Person.PersonID,
FirstName
LastName
});
and fill in the blanks in much the same way.
here's a linq example without using lambda expressions, that includes a group by clause if you prefer it: Linq to sql select into a new class

automapper create.map() to a collection property

How do you map to a collection of property but only interested with the last record of the collection.
Say, something like.
public class ItemDTO <-- destination class
{
public string Name { get; set; }
public decimal PricesPrice { get; set; }
}
public class Item <-- Source class
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Price> Prices { get; set; }
}
public class Price <-- Source class
{
public int Id { get; set; }
public int ItemId { get; set; }
public decimal Price { get; set; }
public virtual Item Item { get; set; }
}
Then I have tried something like this, but doesn't seems to be right.
Mapper.CreateMap<Item, ItemDTO>()
.ForMember(dto => dto.PricesPrice, opt => opt.MapFrom(s => s.Prices.LastOrDefault().Price));
EDIT: And then after that I did a Projection because If I use Mapper.Map() It will return the entire result set which is not what I want, I only want the values I needed. So I did something like this:
Project().To<ItemDTO>()
Well, basically, I want something like this:
from item in SomeDbContext.Items
where item.ItemId == 1
select new ItemDTO
{
Name = item.Name,
PricesPrice = item.Prices.LastOrDefault()
}
Can above code be done using AutoMapper?
I think I understand what you are trying to do now.
Try this
from item in SomeDbContext.Items
where item.ItemId == 1
select Mapper.Map<ItemDTO>(item)
or you could use LINQ
SomeDbContext.Items.Where(i=> i.ItemId == 1).Select(Mapper.Map<ItemDTO>)
Both of these will return you a list of ItemDTO object where the ItemId is 1

Categories

Resources