Ehsan Ghanbari

Experience, DotNet, Solutions

How to query over Icollection<> of a type with linq

When you are implementing many to many relations in SQL, in the case of using entity framework code fist you must use Icollection<> or Ilist<> of an entity. Imagine that you have this classes, an Author class which has a collection of books

 

    public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public ICollection<Books> Books { get; set; }
    }

 

And the Books which has a collection of Authors

 

    public class Books
    {
        public int Id { get; set; }
        public string Title { get; set; }

        public ICollection<Author> Authors { get; set; }
    }

 

And this is your context class

 

    public class ContextClass : DbContext
    {
        public DbSet<Books> Books { get; set; }
        public DbSet<Author> Authors { get; set; }
    }

 

If you want you to create a repository class, to get the books by authors Id, You should act like this

 

    public class Repository
    {
        private ContextClass _contextClass = new ContextClass();
        public IEnumerable<Books> FindBookByAuthor(int authorId)
        {
            var query = _contextClass.Books.Where(b => b.Authors.Any(a => a.Id == authorId));
            return query.ToList();
        }
    }

 

In the lambda expression, you have to use any(), because you have a collection of authors in book class. That's all!

 



How to use PagedList In asp.net MVC

PagedList.Mvc is one of many good paging and sorting packages for ASP.NET MVC, in the below simple example I'm gonna implement it for content (posts) of a blog post, install the PagedList.MVC via Nuget and take a look at this code. This is an action which returns blog posts:

 

       public ActionResult List(int? page)
        {
            var posts = _blogService.GetAllBlogPosts();
            var pageNumber = page ?? 1;
            var onePageOfPosts = posts.ToPagedList(pageNumber, 10);
            ViewBag.OnePageOfPosts = onePageOfPosts;
            return View(posts);
        }

 

 I just defined the OnePageOfPosts  ViewBag and onePageOfPosts.  now in the view, you have to add a line of code:

 

@using PagedList
@using PagedList.Mvc;
@model IEnumerable<BlogViewModel>
@{
      ViewBag.Title = "List";
   }
@foreach (var item in Model)
 {
           @Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.PostId, urlSlug = item.UrlSlug }, null)
           @Html.DisplayTextFor(blog => item.Body)
  }

@Html.PagedListPager((IPagedList)ViewBag.OnePageOfPosts, page => Url.Action("List", new { page }) )

 

if you run this piece of code, you should have something like this in the output:

 

<< First < Previous 1 2 3 4 5 … Next > Last >> 

 



Using Generic type for type casting in F#

In order to validate some input of type object into numeric types, you can use System.Convert in C#. We have them in F# as well! Look at the following function:

 

open System

let validate<'a, 'b> (cast: 'a -> 'b) (x: 'a) =
    try
        cast x |> Some
    with _ -> None

let a = validate int "3423"
let d = validate<obj, decimal> Convert.ToDecimal (null :> obj)
let e = validate<string, DateTime> Convert.ToDateTime "2017-10-10"

 

Validate has been used to convert obj to decimal and even to DateTime. In order to see the result of the following piece of code, you can use it in F#.Net Core console application: 

 

[<EntryPoint>]

let main argv =

    printfn "%A" e // or d and a that has calculated by Validate<,>

    0

 



Domain driven design VS model driven architecture

Domain Driven design(DDDesign) is not the same Model Driven Architecture(MDA). Although The root of both DDDesign and MDA is the same and it is Model Driven Engineering and also both of them aim to solve the problem of converting a 'pure' problem domain model into a full software system. But there are some differences.

Domain Driven Design concentrates on Modeling and solving the Domain problem by Capturing the model from the Ubiquitous language. it is about modeling a domain of knowledge with a high level of abstraction and its focuses are on domain logic and tries to keep the design as much close to the real world. In DDDesign you create the model with the Ubiquitous language so you should understand the business without any technical issues. In another side, model forms the ubiquitous language of DDDesign which explains the domain in a simple form and it's kinda a backbone of DDDesign.

But Model-driven architecture is an approach to building the model of the system. As I mentioned MDA is a kind of domain engineering too. A model is just some taken classes, methods and ... from the problem domain. MDA provides you to use multiple standards such as UML. 

 

but you know it doesn't stop there, I don't know more than these two paragraphs about differences of DDD and MDA! please let me know more about these two architectures and differences by comments, thanks...



What's the DDD-lite?

Based on Vaughn Vernon 's definition, "DDD-Lite is a means of picking and choosing a subset of the DDD tactical patterns, but without giving full attention to discovering, capturing, and enhancing the Ubiquitous Language." most of the DDD-like approaches are not really DDD! If you don’t have bounded contexts so Ubiquitous language(UL) doesn't mean anything and if you have no UL, you won't have business rules.

In DDD, you should concentrate on a domain model and establish a ubiquitous language and use the patterns of DDD. But most of the cases your application is not complex and big enough to apply the whole DDD approach. but for more and different reasons you are going to use DDD patterns. For example when your application doesn't have any complex and different scenarios to separate them as bounded contexts or SubDomains - and you just embrace technical tools, concepts and patterns of DDD like simple entities, services, repositories, aggregates. In these cases, you can use patterns of DDD within your code and call it "DDD-lite".

I started a project about 10 days ago, it's so interesting that I just read about DDD-lite yesterday; but when I designed the architecture of the project, as I'm really interested in DDD I assigned entities as Aggregate and used the repository and layerSupertype patterns, Repository and Service layers. But I don't have any bounded context, value object, subdomain, UL, Domain Service or context map in this project. I've approximately finished the project, I'm gonna to describe the architecture of the project in a few days after hosting in this tag of my blog with "Statos" title.

As usual, it's my pleasure you to correct my mistakes, thanks



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Using Generic type for type casting in F#
Domain driven design VS model driven architecture
What's the DDD-lite?