Mapping the 'count' on child list property in AutoMapper - list

I am working in an ASP.NET MVC 4 application, and have something similar to this for my domain.
public class Party
{
public Cake PartyCake { get; set; }
public List<Candles> CakeCandles { get; set; }
}
I want to map that to the PartyVM which looks like so:
public class PartyVM
{
public string PartyCakeName { get; set; }
public int CandlesCount { get; set; }
}
How can I tell AutoMapper to work out the Count of the list when doing its mappings? I have this, but all this does is tell it to ignore!
Mapper.CreateMap<Party, PartyVM>()
.ForMember(dest => dest.CandlesCount, opt => opt.Ignore());
Thanks.

AutoMapper supports Count out of the box, your destination member is just named incorrectly. If you name your PartyVM property "CakeCandlesCount" it will have the right value.

Related

How to specify the principal entity to which the foreign key refers using the Fluent API?

How to specify the principal entity to which the foreign key refers using the Fluent API?
I am learning the EF Core through the tutorials over here.
I come across the following example:
public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorFK { get; set; }
public Author Author { get; set; }
}
public class SampleContext : DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasForeignKey(p => p.AuthorFK);
}
}
And I can not understand how the EF Core knows that the AuthorFK refers to the Author entity. I.e. if for instance, I would like the AuthorFK to be a foreign key for an entity different from the Author entity, how could I do that?
Surprisingly, the tutorial is wrong there. The correct method is:
modelBuilder.Entity<Book>()
.HasOne(e => e.Author)
.WithMany()
.HasForeignKey(e => e.AuthorFK);
The method shown (modelBuilder.Entity<Book>().HasForeignKey) doesn't exist.
I think when you see this it'll all make sense.

Filter in Sitecore Children in Sitecore

I have this tree structure:
Page1
PageA
PageX
PageY
PageB
Page2
I want Page1 and Page2 as well as all child pages. I have created two classes. In one class using sitecore query
[SitecoreQuery("../*[##templateid={GUID}]", IsRelative = true)]
public virtual IEnumerable<ItemModel> Links { get; set; }
In other ItemModel class getting child pages
public class ItemModel
{
[SitecoreId]
public Guid Id { get; set; }
[SitecoreChildren]
public IEnumerable<SideMenuModel> Children { get; set; }
}
This is working fine but now I want to get only those child pages who have some specific template. Please provide me some solution.
It looks like you have most of the code correct but you need to also apply restrictions to the Children property on the ItemModel class.
You can use a SitecoreQuery on the like you have on the parent model:
public class ItemModel
{
[SitecoreId]
public Guid Id { get; set; }
[SitecoreQuery("./*[##templateid={SideMenuModel-GUID}]", IsRelative = true)]
public virtual IEnumerable<SideMenuModel> ChildItems { get; set; }
}
Or you can use the EnforceTemplate attribute on your SideMenuModel class:
[SitecoreType(TemplateId = "GUID", EnforceTemplate = SitecoreEnforceTemplate.Template)]
public class SideMenuModel
{
[SitecoreId]
public Guid Id { get; set; }
}
public class ItemModel
{
[SitecoreId]
public Guid Id { get; set; }
[SitecoreChildren]
public virtual IEnumerable<SideMenuModel> ChildItems { get; set; }
}
Since you have set EnforceTemplate then using the [SitecoreChildren] attribute means that only items matching the template id will be returned, otherwise they will be skipped.
If you need children of children mapped then you should add [SitecoreChildren] property on your SideMenuModel class as well (or refactor your code so the class references itself) or you could use a "get all descendants query (.//*[##templateid={SideMenuModel-GUID}]) although I would recommend that you ur he Content Search API at this point instead.
You can read more in the blog post about Getting child items with Glass.

Cannot mock .... The profiler must be enabled to mock, arrange or execute the specified target

I have the following in a test (my first ever JustMock test, I might add)...
var template = Mock.Create<MessageType>();
Mock.Arrange(() => template.Subject)
.Returns("This template has Zero tokens.");
Mock.Arrange(() => template.Body)
.Returns("This template has {{number}} of {{tokens}}.");
The class being Mocked looks like this ...
public class MessageType : BaseBusinessEntity
{
public string Body { get; set; }
public int DigestsToBeIncludedOn { get; set; }
public Guid MessageReference { get; set; }
public int MessageTypeId { get; set; }
public string Name { get; set; }
public int PredefinedRecipients { get; set; }
public string Subject { get; set; }
}
When I attempt to run the test I get ...
Error Message: Test method
Genesis.Service.Implementation.Tests.DigestFixture.ShouldCorrectlyExtractTemplateTokens
threw exception: Telerik.JustMock.Core.ElevatedMockingException:
Cannot mock 'System.String get_Subject()'. The profiler must be
enabled to mock, arrange or execute the specified target. Stacktrace:
at
Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo
member) at
Telerik.JustMock.Core.MocksRepository.CheckMethodInterceptorAvailable(IMatcher
instanceMatcher, MethodBase method) at
Telerik.JustMock.Core.MocksRepository.AddArrange(IMethodMock
methodMock) at
Telerik.JustMock.Core.MocksRepository.Arrange[TMethodMock](Expression
expr, Func1 methodMockFactory) at
Telerik.JustMock.Mock.<>c__DisplayClass81.b__6() at
Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func1
guardedAction) at Telerik.JustMock.Mock.Arrange[TResult](Expression1
expression) at
Genesis.Service.Implementation.Tests.DigestFixture.ShouldCorrectlyExtractTemplateTokens()
in
c:\Genesis\Development\Genesis.Service.Implementation.Tests\DigestFixture.cs:line
46
Can anyone point out what I've done wrong?
Be sure you have enabled the profiler from the menu.
While using Visual Studio for writing your tests you will notice the Telerik menu and the JustMock menu-item in it. Once there, you have to check if JustMock is enabled(“Enable JustMock” should be grey, see the example bellow).

Invalid column name error with EF 4.1 Code First

I've been having a problem with this for about a day now, I've searched and found similar problems with their solutions but haven't been able to fix this.
I've seen this done with the Teams example, so I'll do the same. I have a Team:
public abstract class Team
{
[Key]
public int IdTeam { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
I also have a Match object:
public class Match
{
[Key]
public int IdMatch { get; set; }
[ForeignKey("HomeTeam")]
public int IdHomeTeam { get; set; }
[ForeignKey("AwayTeam")]
public int IdAwayTeam { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team AwayTeam { get; set; }
}
Whenever I try to access the name of either team I get an Invalid column name Team_TeamId error. I'm guessing it has something to do with EF and the Foreign Keys not being mapped correctly. I've also seen other people use ICollections, but I don't think I need them for this case.
You have to fix this in the OnModelCreating method. Entity framework can't seem to recognize the foreign keys, so you have to specify it specifically.
public class Entities : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Match>()
.HasRequired(b => b.AwayTeam)
.WithMany()
.HasForeignKey(b => b.IdAwayTeam);
modelBuilder.Entity<Match>()
.HasRequired(b => b.HomeTeam)
.WithMany()
.HasForeignKey(b => b.IdHomeTeam);
}
}
for more information about code first OnModelCreating check this: http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.onmodelcreating(v=vs.103).aspx

ADO.NET Entity Framework multiple FK in one table

I'm using a code from a tutorial to try things out that I'll need in my real project. I have a table in my DataBase with a lot (16) Foreign Keys in it I have to recreate the whole DataBase using ADO.NET EF and now I'm little stuck with this particular case. Here is the code that I'm using for testing purposes:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
//public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
//public int BlogId1 { get; set; }
public virtual Blog Blog1 { get; set; }
//public int BlogId2 { get; set; }
public virtual Blog Blog2 { get; set; }
//public int BlogId3 { get; set; }
public virtual Blog Blog3 { get; set; }
//public int BlogId4 { get; set; }
public virtual Blog Blog4 { get; set; }
}
I've commented the int properties as it seems that I don't need them. Executing this code I get the following:
So there are two thing that concerns me at the moment - is this the way to add multiple Foreign Keys at one table and if so - the two rows underlined with red - why I have Blog_BlogId and Blog_BlogId1 before I get the expected Blog1_.., Blog2_...?
Ok, I lost the post here from where I got the solution but in this particular case it seems to be some sort of naming convention I have to uncomment the commented code and change the names without using numbers or underscore. Then in OnModelCreating event add this code as many times as I need :
modelBuilder.Entity<Post>().HasRequired(c => c.Blog)
.WithMany(m => m.Posts)
.HasForeignKey(c => c.BlogId)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasRequired(c => c.Blogged)
.WithMany()
.HasForeignKey(c => c.BloggedId)
.WillCascadeOnDelete(false);
Notice that I change the property name and the class instance name every time I add new record for foreign key.