NHibernte CreateAlias for 2 multiply class - asp.net-mvc

I have 3 classes: Book, Genre, Authors
public class Book {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual int MfRaiting { get; set; }
public virtual int PageNumber { get; set; }
public virtual IList<Genre> Genres { get; set; }
public virtual Series Series { get; set; }
public virtual Mind Mind { get; set; }
public virtual IList<Author> Authors { get; set; }
public Book() {
Genres = new List<Genre>();
Authors = new List<Author>();
}
}
public class Genre {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Book> Books { get; set; }
public Genre() {
Books=new List<Book>();
}
}
public class Author {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string SurName { get; set; }
public virtual string Biography { get; set; }
public virtual IList<Book> Books { get; set; }
public Author() {
Books=new List<Book>();
}
}
And his classMaps
public class BookMap : ClassMap<Book> {
public BookMap() {
Id(x => x.Id);
Map(x => x.Name);
HasManyToMany(x => x.Genres)
.Cascade.All()
.Table("Book_Genre");
HasManyToMany(x => x.Authors)
.Cascade.All()
.Table("Book_Author");
References(x => x.Series);
HasOne(x => x.Mind).Constrained();
}
}
public class GenreMap : ClassMap<Genre> {
public GenreMap() {
Id(x => x.Id);
Map(x => x.Name);
HasManyToMany(x => x.Books)
.Cascade.All()
.Inverse()
.Table("Book_Genre");
}
}
public class AuthorMap : ClassMap<Author> {
public AuthorMap() {
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.SurName);
Map(x => x.Biography);
HasManyToMany(x => x.Books)
.Cascade.All()
.Inverse()
.Table("Book_Author");
}
}
When i try write in code
var criteria = session.CreateCriteria();
criteria.CreateAlias("Genres", "genre", JoinType.LeftOuterJoin);
it works well, but when i do so
public ActionResult Index()
{
var criteria = session.CreateCriteria<Book>();
criteria.CreateAlias("Genres", "genre", JoinType.LeftOuterJoin);
criteria.CreateAlias("Authors", "author", JoinType.LeftOuterJoin);
criteria.SetResultTransformer(new DistinctRootEntityResultTransformer());
}
i see exception Cannot simultaneously fetch multiple bags. How can I get result of that criteria?
Thank

I resolve this problem! I replace IList on ISet, and replace new List<"Class"> on new HashSet<"Class">
I read this problem here.
http://developer-should-know.tumblr.com/post/118012584847/jpa-fetching-strategies Only one collection that is fetched using JOIN strategy can be of type List, other collection must be of type Set. Otherwise an exception will be thrown:
HibernateException: cannot simultaneously fetch multiple bags

Related

Apply cascade delete in one to many relationship

If I have two required foreign keys in class and these keys compose this class primary key and we have another class contain list of this class how to implement cascade delete in this case entity framework code first
public class Post
{
public int Id { get; set; }
public string ClientName { get; set; }
public JobType JobType { get; set; }
public double JobBudget { get; set; }
public DateTime CreationDate { get; set; }
public string JobDescription { get; set; }
public bool IsAccepted { get; set; }
public string ClientId { get; set; }
public List<Proposal> Proposals { get; set; }
public ApplicationUser Client { get; set; }
}
public class Proposal
{
public string FreelancerId { get; set; }
public int PostId { get; set; }
public bool IsAccepted { get; set; }
public ApplicationUser Freelancer { get; set; }
public Post Post { get; set; }
}
public PostConfigurations()
{
Property(p => p.ClientName)
.IsRequired();
Property(p => p.JobType)
.IsRequired();
Property(p => p.JobBudget)
.IsRequired();
Property(p => p.CreationDate)
.IsRequired();
Property(p => p.JobDescription)
.IsRequired()
.HasMaxLength(255);
HasOptional(p => p.Proposals)
.WithOptionalDependent()
.WillCascadeOnDelete(true)
}
public class ProposalConfigurations : EntityTypeConfiguration<Proposal>
{
public ProposalConfigurations()
{
HasKey(p => new { p.FreelancerId, p.PostId });
Property(p => p.FreelancerId)
.IsRequired();
Property(p => p.PostId)
.IsRequired();
}
}
I tried many things, but failed, can you please help?

Automapper not mapping my list properties

In my MVC5 project I use automapper to map my viewmodels to my models. But it seems that I'm doing something wrong, because not all my properties are mapped.
Here is my View Model
public class PlanboardViewModel
{
public int Id { get; set; }
[Display(Name = "Titel")]
public string Title { get; set; }
[Display(Name = "Omschrijving")]
public string Description { get; set; }
[Display(Name = "Verzoektype")]
public int AbsenceTypeId { get; set; }
public List<PlanboardEventMapViewModel> EventMap { get; set; }
public List<PlanboardEventDetail> EventDetails { get; set; }
public List<PlanboardRequest> PlanboardRequests { get; set; }
}
I use a separate class for my profiles:
public class PlanboardMappingProfile : Profile
{
protected override void Configure()
{
//CreateMap<AbsenceType, AbsenceTypeViewModel>();
//.ForAllMembers(opt => opt.Condition(s => !s.IsSourceValueNull));
CreateMap<PlanboardViewModel, Planboard>()
.ForMember(dest => dest.CSVHPlanboardEventDetail, opt => opt.MapFrom(src => src.EventDetails))
.ForMember(dest => dest.CSVHPlanboardEventMap, opt => opt.MapFrom(src => src.EventMap))
.ForMember(dest => dest.CSVHPlanboardRequest, opt => opt.MapFrom(src => src.PlanboardRequests));
CreateMap<PlanboardEventMapViewModel, PlanboardEventMap>();
}
}
In my repository I have the following code:
public int Create(PlanboardViewModel planboardViewModel)
{
try {
// map the viewmodel to the planboard model
// Map the planboards to the view model
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<PlanboardMappingProfile>();
cfg.CreateMap<PlanboardViewModel, Planboard>();
cfg.CreateMap<PlanboardEventMapViewModel, PlanboardEventMap>();
});
IMapper mapper = config.CreateMapper();
Planboard planboard = mapper.Map<Planboard>(planboardViewModel);
// Some more code here
When I submit the page and use the debugger, It shows that planboardViewModel has a list of values for PlanboardEventMapViewModel, PlanboardEventDetail, PlanboardRequest. The system is not telling me that there are any errors. When I check planboard after the mapping, it does not show any values for CSVHPlanboardEventDetail, CSVHPlanboardEventMap and CSVHPlanboardRequest.
EDIT
My PlanboardModel is created DB First EF6:
public partial class Planboard
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Planboard()
{
this.CSVHPlanboardEventDetail = new HashSet<PlanboardEventDetail>();
this.CSVHPlanboardEventMap = new HashSet<PlanboardEventMap>();
this.CSVHPlanboardRequest = new HashSet<PlanboardRequest>();
}
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int StatusID { get; set; }
public Nullable<int> AbsenceTypeID { get; set; }
public virtual AbsenceType AbsenceTypes { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PlanboardEventDetail> CSVHPlanboardEventDetail { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PlanboardEventMap> CSVHPlanboardEventMap { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PlanboardRequest> CSVHPlanboardRequest { get; set; }
}

Fluent API One to Many mapping table

It's really helpful if anyone could explain me how to create a mapping (associated)table for one to many relationship using Fluent API.`
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
public List<Image> Images { get; set; }
}
public class Image
{
public int ID { get; set; }
public string Name { get; set; }
public List<Category> Category{ get; set; }
The mapping table should contain CategoryID and ImageID.
The solution should be something similar to this. (This is for many to many)
modelBuilder.Entity<Category>()
.HasMany(c => c.Images).WithMany(i => i.Categories)
.Map(t => t.MapLeftKey("CategoryID")
.MapRightKey("ImageID")
.ToTable("CategoryImage"));
I want Fluent API to create new mapping table for the below relationship.
public class Category
{
public List<Image> Images{get; set;}
}
public class Image
{
public Category Category{ get; set; }
}
Adding NewTable:
modelBuilder
.Entity<NewTable>()
.HasRequired(_ => _.Category)
.WithMany()
.HasForeignKey(_ => _.CategoryId);
modelBuilder
.Entity<Image>()
.HasRequired(_ => _.NewTable)
.WithMany(_ => _.Images)
.HasForeignKey(_ => _.NewTableId)
public class NewTable
{
public int ID { get; set; }
public int CategoryId { get; set; }
public List<Image> Images { get; set; }
public virtual Category Category { get; set; }
}
public class Image
{
public int ID { get; set; }
public string Name { get; set; }
public List<Category> Categories { get; set; }
public int NewTableId { get; set; }
public virtual NewTable NewTable { get; set; }
}

Linq-To-Nhibernate multiples joins with conditionals

I'm using Fluent-Nhibernate version 1.3 and I'm trying to make a query envolving 5 tables. I created a sql query for an oracle database and I'm trying to replicate with linq-to-nhibernate.
Following a sample of my entities and mapping.
Entities:
public class A
{
public virtual int idA { get; set; }
public virtual String codA { get; set; }
public virtual String tipoA { get; set; }
public virtual IList<B> listB { get; set; }
}
public class B
{
public virtual C objectC { get; set; }
public virtual A objectA { get; set; }
public virtual DateTime dtBegin { get; set; }
public virtual DateTime dtEnd { get; set; }
}
public class C
{
public virtual int idC { get; set; }
public virtual String codeC { get; set; }
public virtual IList<B> listB { get; set; }
public virtual IList<D> listD { get; set; }
}
public class D
{
public virtual C objectC { get; set; }
public virtual string flgD { get; set; }
public virtual DateTime dtBegin { get; set; }
public virtual DateTime dtEnd { get; set; }
public virtual E objectE { get; set; }
}
public class E
{
public virtual int idE { get; set; }
public virtual String dsE { get; set; }
public virtual DateTime dtBegin { get; set; }
public virtual DateTime dtEnd { get; set; }
public virtual IList<D> listD { get; set; }
}
My mapping:
class AMap : ClassMap<A>
{
public AMap()
{
Table("A");
Id(x => x.idA, "ID_A").GeneratedBy.Sequence("StringA");
Map(x => x.tipoA, "TP_A");
Map(x => x.codA, "CODE_A");
HasMany(x => x.listB).Cascade.All().KeyColumn("ID_A");
}
}
class BMap : ClassMap<B>
{
public BMap()
{
Table("B");
CompositeId()
.KeyReference(x => x.objectC, "ID_C")
.KeyReference(x => x.objectA, "ID_A")
.KeyProperty(x => x.dtBegin, "DT_BEGIN");
Map(x => x.dtEnd, "DT_END");
}
}
class CMap : ClassMap<C>
{
public CMap()
{
Table("C");
Id(x => x.idC, "ID_C").GeneratedBy.Sequence("StringC");
Map(x => x.codeC, "CODE_C");
HasMany(x => x.listB).Cascade.All().KeyColumn("ID_C");
HasMany(x => x.listD).Cascade.All().KeyColumn("ID_D");
}
}
class DMap : ClassMap<D>
{
public DMap()
{
Table("D");
CompositeId()
.KeyReference(x => x.objectC, "ID_C")
.KeyProperty(x => x.flgD, "FLG_D")
.KeyProperty(x => x.dtBegin, "DT_BEGIN");
References(x => x.objectE, "CODE_E");
Map(x => x.dtEnd, "DT_END");
}
}
class EMap : ClassMap<E>
{
public EMap()
{
Table("E");
Id(i => i.idE, "ID_E").GeneratedBy.Assigned();
Map(m => m.dsE, "DSC_E");
Map(m => m.dtBegin, "DT_BEGIN");
Map(m => m.dtEnd, "DT_END");
HasMany(x => x.listD).Cascade.All().KeyColumn("ID_E");
}
}
My SQL Query(it works):
SELECT C.CODE_C, E.CODE_E, E.DT_BEGIN
FROM TABLEA A, TABLEB B, TABLEC C, TABLED D, TABLEE E
WHERE A.CODE_A = '0000' AND A.ID_A = B.ID_A AND B.ID_C = C.ID_C AND B.DT_END IS NULL
AND C.ID_C = D.ID_C AND D.DT_END IS NULL AND D.CODE_E = E.CODE_E AND E.DT_END IS NULL;
I tried to use multiple join but then some relathionship are collections so I would have to make a where inside the join.
So my question is: is possible to make this same Sql query as linq-to-nhibernate or is better to make a sequence of selects? And no i can't change the database.
Thanks in advance.
the is null query is only possible using DateTime? as type
var query = from b in B
from c in b.C
from d in c.listD
from e in d.E
where b.A.Code == "0000" && b.EndDate == null & ...
select new { Ccode = c.Code, Ecode = e.Code, E_BeginDate = e.BeginDate }
Update: to answer the third comment
grouping the results has to be done in memory because grouping in sql can only return aggregations
var results = query.AsEnumerable()
.GroupBy(a => a.Ccode, a => a.Ecode, (key, values) => new { Ccode = Key, Ecodes = values.ToList() })
.List();

Domain Modeling Question using C# with Entity Framework CTP 4

I am trying to model out a album that has a collection of photos. Each Album will have a collection of Photos and a Photo that is a thumb. This is what I have but EF does not seem to like it:
public class Album : IEntity {
private DateTime _dateCreated;
public Album() {
_dateCreated = SystemTime.Now();
Photos = new List<Photo>();
}
public long Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public DateTime DateCreated
{
get { return _dateCreated; }
set { _dateCreated = value; }
}
public virtual Site Site { get; set; }
public virtual Photo Thumbnail { get; set; }
public virtual ICollection<Photo> Photos { get; set; }
}
public class Photo : IEntity {
public Photo() {
_dateCreated = SystemTime.Now();
}
private DateTime _dateCreated;
public long Id { get; set; }
public string Caption { get; set; }
public string FileName { get; set; }
public DateTime DateCreated
{
get { return _dateCreated; }
set { _dateCreated = value; }
}
public virtual Album Album { get; set; }
}
public class AlbumMap : EntityConfiguration<Album>
{
public AlbumMap()
{
HasKey(x => x.Id);
Property(x => x.Id).IsIdentity();
Property(x => x.Location).IsVariableLength().HasMaxLength(80);
Property(x => x.Name).IsVariableLength().HasMaxLength(80).IsRequired();
Property(x => x.DateCreated);
MapSingleType(a => new
{
a.Id,
SiteId = a.Site.Id,
ThumbnailId = a.Thumbnail.Id,
a.Location,
a.Name,
a.DateCreated
}).ToTable("Albums");
}
}
public class PhotoMap : EntityConfiguration<Photo>
{
public PhotoMap()
{
HasKey(x => x.Id);
Property(x => x.Id).IsIdentity();
Property(x => x.FileName).IsVariableLength().HasMaxLength(255).IsRequired();
Property(x => x.Caption).IsVariableLength().HasMaxLength(255);
Property(x => x.DateCreated);
MapSingleType(a => new
{
a.Id,
SiteAlbumId = a.Album.Id,
a.FileName,
a.Caption,
a.DateCreated
}).ToTable("AlbumPhotos");
}
}
Am I missing something or does this look right? I am expecting EF to generate a 1 to many in my database but it keeps creating a reference table between Album and Photos (Album_Photos) but this should not be a many-to-many. Any help would be great.
By convention, EF code first does not create a link table in typical one to many scenario, the reason that you are getting it is because your associations between Album and Photo objects has been taken by EF as being a kind of many to many association:
Each album has a collection of Photos and also each Photo has a collection of Albums that this photo is a thumbnail for (although the related navigation property is not explicitly specified on Photo class and only Album has a Thumbnail property).
Solution:
As of EF CTP4, the only way to fix this is by leveraging Fluent API, but before that, I modify your model a little bit and add two explicit FKs to your model to give you ultimate flexibility to work with your objects. They are AlbumId on Photo and ThumbnailId on Album:
public class Photo {
public long Id { get; set; }
public string Caption { get; set; }
public string FileName { get; set; }
public DateTime DateCreated { get; set; }
public long AlbumId { get; set; }
public virtual Album Album { get; set; }
}
public class Album {
public long Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public DateTime DateCreated { get; set; }
public long ThumbnailId { get; set; }
public virtual Photo Thumbnail { get; set; }
public virtual ICollection<Photo> Photos { get; set; }
}
public class PhotoMap : EntityConfiguration<Photo> {
public PhotoMap()
{
this.HasRequired(p => p.Album)
.WithMany(a => a.Photos)
.HasConstraint((p, a) => p.AlbumId == a.Id);
Property(x => x.FileName).IsVariableLength().HasMaxLength(255)
.IsRequired();
Property(x => x.Caption).IsVariableLength().HasMaxLength(255);
MapSingleType(p => new {
p.Id,
SiteAlbumId = p.AlbumId,
p.FileName,
p.Caption,
p.DateCreated
})
.ToTable("Photo");
}
}
public class AlbumMap : EntityConfiguration<Album> {
public AlbumMap()
{
this.HasRequired(a => a.Thumbnail)
.WithMany()
.WillCascadeOnDelete(false)
.HasConstraint((a, p) => p.Id == a.ThumbnailId);
Property(x => x.Location).IsVariableLength().HasMaxLength(80);
Property(x => x.Name).IsVariableLength().HasMaxLength(80).IsRequired();
MapSingleType(a => new {
a.Id,
a.ThumbnailId,
a.Location,
a.Name,
a.DateCreated
})
.ToTable("Album");
}
}
This results to the following desired schema:

Resources