I have a parent object(brand) with list of 5 child object(campaign):
Brand response = await _brandRepository.GetAsync(request.Id);
//other properties mapped fine, but Campaing is null..
var result = _mapper.Map<BrandDto>(response);
return result;
I have these definations for mapping:
CreateMap<Domain.Entity.Campaign, CampaignDto>();
CreateMap<Domain.Entity.Brand, BrandDto>();
objects:
public class BrandDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<CampaignDto> Campaing { get; set; }
}
public class CampaignDto
{
public int Id { get; set; }
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public CampaignDto ParentCampaign { get; set; }
public BrandDto Brand { get; set; }
}
entities:
public class Brand : SqlEntityBase
{
public string Name { get; set; }
public List<Campaign> Campaign { get; set; } = new List<Campaign>();
}
public class Campaign : SqlEntityBase
{
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public Guid ImpressionId { get; set; }
public string Name { get; set; }
public EntryStatus Status { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime CreatedOn { get; set; }
public Brand Brand { get; set; }
public Campaign ParentCampaign { get; set; }
}
If I map child object manually it works fine, but its not cool
how can I make this proper way?
Related
I have below class with Header and Child class. I would like to know how to serialize child object using newtonsoft.I have tried below child object, but its return only one record where as child object contain 4 record
public class StyleBomLeatherSetupHeader
{
public int StyleStockID { get; set; }
public List<StyleBomLeatherSetup> Details { get; set; }
}
public class StyleBomLeatherSetup
{
public int StyleBomLeatherID { get; set; }
public int StyleStockID { get; set; }
public int? TypeID { get; set; }
public int? PartNoID { get; set; }
public int? ComponentID { get; set; }
public int? LeatherID { get; set; }
public int? ColorID { get; set; }
public decimal? Norms { get; set; }
public decimal? Wastage { get; set; }
public decimal? TotalNorms { get; set; }
}
Serialize json object:-
styleBomLeatherSetupHeader.StyleStockID = styleStockSetup.StyleStockID;
styleBomLeatherSetupHeader.Details = styleBomLeatherSetups;
protected StyleBomLeatherSetupHeader styleBomLeatherSetupHeader { get; set; } = new StyleBomLeatherSetupHeader();
string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);
After you have the header object setup, you can point to the child list with your property "Details". And with that been said, you can serialize just that property, like this:
string detailsJson =JsonConvert.SerializeObject(styleBomLeatherSetupHeader.Details);
public class StyleBomLeatherSetupHeader
{
public StyleBomLeatherSetupHeader ()
{
Details = new List<StyleBomLeatherSetup>();
}
public int StyleStockID { get; set; }
public IList<StyleBomLeatherSetup> Details { get; set; }
}
public class StyleBomLeatherSetup
{
public int StyleBomLeatherID { get; set; }
public int StyleStockID { get; set; }
public int? TypeID { get; set; }
public int? PartNoID { get; set; }
public int? ComponentID { get; set; }
public int? LeatherID { get; set; }
public int? ColorID { get; set; }
public decimal? Norms { get; set; }
public decimal? Wastage { get; set; }
public decimal? TotalNorms { get; set; }
}
Then
styleBomLeatherSetupHeader.StyleStockID=styleStockSetup.StyleStockID;
foreach(styleBomLeatherSetup in styleBomLeatherSetups)
{
styleBomLeatherSetupHeader.Details.Add(new StyleBomLeatherSetup{
// map your properties.
});
}
string json = JsonConvert.SerializeObject(styleBomLeatherSetupHeader);
public IEnumerable<Parties> GetAll()
{
return database.Parties;
}
Works very well and the output is:
But when I Include another table by foreignkey like this:
public IEnumerable<Parties> GetAll()
{
return database.Parties.Include(i=>i.User);
}
It does not work, it returns first value of the table and nothing else,the output is :
Users.cs :
public partial class Users
{
public Users()
{
Parties = new HashSet<Parties>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Avatar { get; set; }
public string Biography { get; set; }
public string Password { get; set; }
public virtual ICollection<Parties> Parties { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
Parties.cs :
public partial class Parties
{
public Parties()
{
Image = new HashSet<Image>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime PartyDate { get; set; }
public DateTime CreatedDate { get; set; }
public int ParticipantCount { get; set; }
public int MaxParticipant { get; set; }
public string PartySplash { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool EntranceFree { get; set; }
public int? FreeParticipant { get; set; }
public int? FreeParticipantMax { get; set; }
public int UserId { get; set; }
public virtual Users User { get; set; }
public virtual ICollection<Image> Image { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
As you can see on the 2nd picture it interrupts at first row of the table.
I have added this answer based on Vidmantas's comment. ReferenceLoopHandling should be ignored like this in startup.cs:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
I am trying to map a model to a view, but I receive the error above when I am trying to display all my elements, since Automapper doesn't recognize the IEnumerable I think. I receive the error when I am trying to map FixedAssets to FixedAssetsView and FixedAssetsView to FixedAssets.
Here are the objects I am trying to map:
FixedAssets
public class FixedAssets : IEntityBase
{
public int ID { get; set; }
public string name { get; set; }
public virtual ICollection<Category> category { get; set; }
public string serialNo { get; set; }
public string provider { get; set;
public DateTime acquisitionDate { get; set; }
public DateTime warrantyEnd { get; set; }
public int inventoryNo { get; set; }
public string allocationStatus { get; set; }
public string owner { get; set; }
public DateTime allocationDate { get; set; }
public string serviceStatus { get; set; }
public string serviceResolution { get; set; }
public FixedAssets()
{
this.category = new HashSet<Category>();
}
}
FixedAssetsView
public class FixedAssetsView
{
public int ID { get; set; }
public string name { get; set; }
public virtual ICollection<CategoryView> category { get; set; }
public string serialNo { get; set; }
public string provider { get; set; }
public DateTime acquisitionDate { get; set; }
public DateTime warrantyEnd { get; set; }
public int inventoryNo { get; set; }
public string allocationStatus { get; set; }
public string owner { get; set; }
public DateTime allocationDate { get; set; }
public string serviceStatus { get; set; }
public string serviceResolution { get; set; }
}
Category
public class Category : IEntityBase
{
public int ID { get; set; }
public string categoryName { get; set; }
public virtual ICollection<FixedAssets> fixedasset { get; set; }
public Category()
{
this.fixedasset = new HashSet<FixedAssets>();
}
}
CategoryView
public class CategoryView
{
public int ID { get; set; }
public string categoryName { get; set; }
public virtual ICollection<FixedAssetsView> fixedasset { get; set; }
}
Automapper configuration
Mapper.Initialize(x =>
{
x.CreateMap<FixedAssets, FixedAssetsView>();
x.CreateMap<FixedAssetsView, FixedAssets>();
x.CreateMap<Category, CategoryView>();
x.CreateMap<CategoryView, Category>();
});
I believe you need a .ForMember in your Mapper initialization.
eg:
Mapper.CreateMap<IEnumerable<Source>, IEnumerable<Target>>()
.ForMember(f => f, mp => mp.MapFrom(
mfrom => mfrom.Select(s => AutoMapper.Mapper.Map(s, new Target())
)
);
I have 2 models:
public partial class Movie
{
public Movie()
{
TimeTables = new HashSet<TimeTable>();
}
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public int MovieGenre { get; set; }
public string MoviePicture { get; set; }
public string MovieDescription { get; set; }
public string MovieShortText { get; set; }
public bool? MovieIs3d { get; set; }
public bool? MovieIsImax { get; set; }
public int MovieLanguage { get; set; }
public bool? MovieSubtitled { get; set; }
public int? MovieMinimalAge { get; set; }
public bool? MovieHasDrugs { get; set; }
public bool? MovieHasViolence { get; set; }
public bool? MovieHasSex { get; set; }
public bool? MovieHasSwearing { get; set; }
public bool? MovieIsScary { get; set; }
public bool? MovieHasDiscrimination { get; set; }
public string MovieTrailer { get; set; }
public int MovieLength { get; set; }
public int? Genre_GenreId { get; set; }
public int? Language_LanguageId { get; set; }
public virtual Genre Genre { get; set; }
public virtual Language Language { get; set; }
public virtual ICollection<TimeTable> TimeTables { get; set; }
}
And:
public partial class TimeTable
{
public TimeTable()
{
Reservations = new HashSet<Reservation>();
}
public int TimeTableId { get; set; }
public int MovieId { get; set; }
public int RoomId { get; set; }
public int SeatsAvaible { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public virtual Movie Movie { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
public virtual Room Room { get; set; }
}
I want to show all the records from Movie which have one or more records in TimeTable and where StartDate.date == [given datetime].
With a simple query the movies are showing multiple times. I have tried a distinct() but that changes nothing.
Anybody here who have the solution?
Current query:
var times2 =
(from s in timetablerepo.TimeTables
orderby s.StartTime.TimeOfDay
where s.StartTime.Date == datetime.Date
select s).Distinct().ToList();
Why not start with movies first and filter by timetable:
var times = timetablerepo.Movies
.Where(m => m.TimeTables.Any(t => t.StartDate.Date == <yourdate>));
Table 1: Articles
Table 2: ArticleCategories
how do I represent the relationship between the two tables which is a 1->1 relationship:
I can do the following, but I'm not sure it's the correct way :
public class Article
{
public int ArticleIndex { get; set; }
public int Category { get; set; }
public Guid User { get; set; }
public int Parent { get; set; }
public int Level { get; set; }
public int Order { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateExpires { get; set; }
public bool Show { get; set; }
public string Title { get; set; }
public string TitleHtml { get; set; }
public string Content { get; set; }
public string ContentHtml { get; set; }
public string ShortTitle { get; set; }
public ArticleCategory Category { get; set; }
}
public class ArticleCategory
{
public int CategoryIndex { get; set; }
public string Name { get; set; }
}
By convention, Code First expects an Id property for each class/table. Then you can do something like this:
public class Article
{
public int Id { get; set; }
public int ArticleIndex { get; set; }
public int Category { get; set; }
public Guid User { get; set; }
public int Parent { get; set; }
public int Level { get; set; }
public int Order { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateExpires { get; set; }
public bool Show { get; set; }
public string Title { get; set; }
public string TitleHtml { get; set; }
public string Content { get; set; }
public string ContentHtml { get; set; }
public string ShortTitle { get; set; }
public int ArticleCategoryId { get; set; }
public virtual ArticleCategory ArticleCategory { get; set; }
}
public class ArticleCategory
{
public int Id { get; set; }
public int CategoryIndex { get; set; }
public string Name { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
Note the virtual keyword. EF Code First needs this so it can perform its magic behind the scenes.
Now, if you are working with an Article, you can get all it's category info by doing article.ArticleCategory, and if you have an ArticleCategory you can find out what article it refers to with articleCategory.Articles.Single().
For more info, see this article by Scott Gu:
http://weblogs.asp.net/scottgu/archive/2010/12/08/announcing-entity-framework-code-first-ctp5-release.aspx