Fluent Hibernate One-To-One mapping issue - c#-4.0

I am not sure how to map below given entities.
Below are the tables.
Employee { ID, Name, Role_ID } (Role_ID is foreign key from Role table)
Role {Role_ID, Name }
Below are the classes:
class Employee
{
public virtual string ID { get; set; }
public virtual string Name { get; set; }
public virtual Role EmpRole { get; set; }
}
class Role
{
public virtual string RoleID { get; set; }
public virtual string Name { get; set; }
}
Below are the Mappings:
public class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Table("Employee");
Id(x => x.ID, "ID");
Map(x => x.Name, "NAME");
//for relationship not sure which mapping to be used???
}
}
public class RoleMap : ClassMap<Role>
{
public RoleMap()
{
Table("Role");
Id(x => x.RoleID, "ROLE_ID");
Map(x => x.RoleID, "ROLE_ID");
Map(x => x.Name, "ROLE_NAME");
//For relationship not sure what to be used????
}
}
Scenario : One Employee will have one role. One Role can be assigned to multiple employee.
Please suggest me how to write the relationship for both entities?

You are facing the most common scenario. The mapping in this case would be many-to-one which in fluent is represented with .References()
public EmployeeMap()
{
Table("Employee");
Id(x => x.ID, "ID");
Map(x => x.Name, "NAME");
References(x => x.EmpRole , "Role_ID");
}
The best overview (I am aware about) is available here:
Mapping-by-Code - ManyToOne by Adam Bar
Suprisingly this post is not about fluent NHibernate but about mapping by code. The second half however, compares with fluent - and provides really comprehensive overivew. Small snippet:
References(x => x.PropertyName, "column_name")
.Class<ClassName>()
.Cascade.SaveUpdate()
.Fetch.Join()
.Update()
.Insert()
.ReadOnly()
.Access.Field()
.Unique()
.OptimisticLock()
.LazyLoad(Laziness.Proxy)
.PropertyRef(x => x.PropertyRef)
.NotFound.Ignore()
.ForeignKey("column_fk")
.Formula("arbitrary SQL expression")
.Index("column_idx")
.Not.Nullable()
.UniqueKey("column_uniq");
In case you would search for NHibernate doc (fluent operates on top of it) you should check the:
5.1.10. many-to-one
If you want Fluent-NHibernate doc:
Fluent mapping
Finally, if you like to see which Employees belong to each Role, you can extend your POCO:
class Role
{
public virtual string RoleID { get; set; }
public virtual string Name { get; set; }
public virtual IList<Employee> Employees { get; set; }
}
And map it as a <bag>.
HasMany(x => x.Employees)
.KeyColumn("Role_ID")
.Inverse()
.BatchSize(25)
See:
6.1. Persistent Collections (NHibernate doc for one-to-many)
Mapping-by-Code - Set and Bag - again by Adam Bar, second half about fluent

Related

Automapper & EF Core: One-to-many relationship exposed by DTO

I effectively have the following entities defined:
public class Order
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Part
{
public int Id { get; set; }
public string Description { get; set; }
public int? OrderId { get; set; }
public Order Order { get; set; }
}
They are configured so that the OrderId in Part is linked to the Order Id:
// Order Model Builder
var orderModelBuilder = modelBuilder.Entity<Order>()
.ToTable("Orders");
orderModelBuilder.HasKey(i => i.Id);
orderModelBuilder.HasMany<Part>()
.WithOne()
.HasForeignKey(i => i.OrderId);
// Part Model Builder
var partModelBuilder = modelBuilder.Entity<Part>()
.ToTable("Parts");
partModelBuilder.HasKey(i => i.Id);
partModelBuilder.HasOne(i => i.Order)
.WithMany()
.HasForeignKey(i => i.OrderId);
Now I would like to map these to a detailed order DTO which includes a collection of parts for an order:
public class PartDto
{
public int Id { get; set; }
public string Description { get; set; }
}
public class OrderDetailsDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<PartDto> Parts { get; set; }
}
Currently, I use Automapper's ProjectTo() to handle queries so I can query what I want and get a list of orders back already mapped to my desired DTO. Now, I want to add Parts to that query so I can get all of the orders back with parts in one query without having to loop through orders and individually fetch the parts for each order returned. I could easily do that if List was part of the Order entity class but adding it at this stage isn't really an option.
CreateMap<Part, PartDto>()
.ForMember(d => d.Id, a => a.MapFrom(s => s.Id))
.ForMember(d => d.Description, a => a.MapFrom(s => s.Description))
;
CreateMap<Order, OrderDetailsDto>()
.ForMember(d => d.Id, a => a.MapFrom(s => s.Id))
.ForMember(d => d.Name, a => a.MapFrom(s => s.Name))
.ForMember(d => d.Parts, a => a.MapFrom(s => ?????))
;
.
..
...
await dbContext.Set<Order>().Where(...).ProjectTo<OrderDetailsDto>(configurationProvider).ToListAsync()
I know I can get shadow variables using EF.Property(object, name) but not sure how to load a restricted collection (dbContext.Set.Where(i => i.OrderId == orderId)). Any suggestions would be greatly appreciated!
--
I'm also open to adding another Entity class if there is a way to make it exist next to the existing entity. So far, I can't find a way to do that without EF Core complaining that it can only have one entity per class (without a discriminator column which would defeat the purpose!).

DDD/CQRS, Entity has access to Query, Command?

public class PageRoleService
{
public void SetRoles(Page page, User activeUser)
{
var rb = page.Project.ProjectType.GetRoleFor(activeUser.UserType);
page.RolesForPage.Add(activeUser, rb);
var managers = GetAllManagersOf(activeUser);
foreach (var m in managers)
{
page.RolesForPage.Add(m, rb);
}
}
}
public class Project : Entity
{
public ProjectType ProjectType { get; set; }
public IList<Page> Pages { get; set; }
}
public class Page : Entity
{
public string Name { get; set; }
public Project Project { get; set; }
public IDictionary<User, RoleBehaviour> RolesForPage { get; set; }
}
public class ProjectType : Entity
{
public IQueryProcessor QueryProcessor { get; set; }
public IList<RoleBehaviour> RoleBehaviours { get; set; }
public RoleBehaviour GetRoleFor(USerType userType)
{
var behaviour = return QueryProcessor.Execute(new GetRolesByUserAndProjectTypeQuery() {
ProjectType = this,
UserType = userType
});
// Filter behaviour attributes for project type properties, business rules, etc...
// FilterBehaviour(behaviour);
return behaviour;
}
}
public class GetRolesByUserAndProjectTypeQuery
{
public UserType UserType { get; set; }
public ProjectType ProjectType { get; set; }
}
public class GetRolesByUserAndProjectTypeQueryHandler
{
public Db Db { get; set; }
public RoleBehaviour Execute(GetRolesByUserAndProjectTypeQuery query)
{
return Db.FirstOrDefault(r => r.UserType == query.UserType && r.ProjectType == query.projectType);
}
}
public class RoleBehaviour : Entity
{
public Role ROleForArea1 { get; set; }
public Role ROleForArea2 { get; set; }
public UserType UserType { get; set; }
public ProjectType ProjectType { get; set; }
public IDictionary<string, string> Attributes { get; set; }
}
public enum UserType
{
A,
B,
C,
D
}
public class Role : Entity
{
public IList<string> Permissions { get; set; }
}
I don't use repository, no need data abstraction, I use CQRS for crud operations. (CreateProjectCommand, GetRolesByUserAndProjectTypeQuery, etc..)
Users related a lot of project and page. Users have more than role for each Page Entity and is dynamically created when user (client) request to fetch All projects page or single page item.
My Page Role Service determinates page roles for active user and its managers. My MVC Controller use PageRoleService.
PageRoleService is Application Service or Domain Service or .....?
QueryProcessor in Entity (ProjectType) is invalid approach? How can handle this/their problems without lazy or eager loading?
RoleBehaviour is Entity or Value Object?
PageRoleService is a service or business logic in domain?
I know that I'm some years later, but:
I would put away the base class Entity, because it looks that this are just Dtos returned by the queryhandler (infact GetRolesByUserAndProjectTypeQueryHandler.Execute returns a RoleBehaviour).
Given this, I think that:
PageRoleService is a simple service that completes a Dto, hence it looks a kind of factory
Given that ProjectType here has two different roles (a Dto and Entity, and this is against CQRS), if:
it's a Dto, then use a service/factory/ORM to load extra data on it
it's an Entity, try to load all the data that's needed by it. This because there're great changes that you'll need it on the way to execute your command (great explanation about DDD and entities).
The object has it's own identity? Has it an Id that, even if things will change, remains the same? Looking at it, it looks just a Dto, with nothing really interesting (at business level).
see 1.

Entity Framework - Single Entity to Multiple Tables

I am having some difficulty in mapping single entity to a two different tables in a Entity Framework out of which one is optional to give a quick overview.
I have one main table which is of a core table that lot of our applications in our company uses it, so we really don't want to make any changes to this table.
In our new application we needed a few more columns to support some of the features we are adding.
I have created a single Entity Model that will save information to both these tables, it is working fine when both these tables has the records (related by primary key and foreign key)
But for the historical record this new table will not have a associated record and not able to fetch any entity set.
Below is the code snippet.
public class ModelTable
{
public string PatientID { get; set; }
public string Diagnosis1 { get; set; }
public string Diagnosis2 { get; set; }
public string Diagnosis3 { get; set; }
public string Diagnosis4 { get; set; }
public string Diagnosis5 { get; set; }
public string Diagnosis6 { get; set; }
public string Diagnosis7 { get; set; }
public string Diagnosis8 { get; set; }
}
public class ModelTableMap : EntityTypeConfiguration<ModelTable>
{
public ModelTableMap()
{
//Table1
this.Map(model =>
{
model.Properties(table1 => new
{
table1.Diagnosis1,
table1.Diagnosis2,
table1.Diagnosis3,
table1.Diagnosis4,
table1.Diagnosis5,
table1.Diagnosis6
});
model.ToTable("Table1");
});
//Optional Table
this.Map(model =>
{
model.Properties(table2 => new
{
table2.Diagnosis7,
table2.Diagnosis8,
});
model.ToTable("Table2");
});
this.HasKey(type => type.PatientID);
this.Property(type => type.PatientID).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(type => type.Diagnosis1).HasColumnName("Diag1");
this.Property(type => type.Diagnosis1).HasColumnName("Diag2");
this.Property(type => type.Diagnosis1).HasColumnName("Diag3");
this.Property(type => type.Diagnosis1).HasColumnName("Diag4");
this.Property(type => type.Diagnosis1).HasColumnName("Diag5");
this.Property(type => type.Diagnosis1).HasColumnName("Diag6");
this.Property(type => type.Diagnosis1).HasColumnName("Diag7");
this.Property(type => type.Diagnosis1).HasColumnName("Diag8");
}
}
If I split these tables into a two different POCO classes and specify the relationshipt it is working fine.
But I want to achieve this with Single Entity, since functionally it is a same table.
Please provide any guidance or if I am doing any wrong and please bare with my English is not that good.
Thanks
Sathish
Entity splitting in current EF version requires records in both tables. If you want to use entity splitting you must create empty record for all existing records from the first table. Otherwise you cannot use entity splitting.

Entity Framework 4.0 CTP5 Many to Many relation ship with a help table?

i have a question about EF4 again :) sorry i can't find any thing on the net.
The question is i am using CTP5 Code Only to map (many to many), how do i do it???
But i am doing the old fashion way, i mean i have three tables:
Users
Companies.
UsersToCompanies -> (UserId, CompanyId)
How do i map this, it will be really appreciated if you would show me the code example to it,
from POCO's to Mapping.
This is the error i receive...
This is my entities
public class User
{
public int UserId { get; set; }
public int? UserRoleId { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
public DateTime InsertDate { get; set; }
public virtual UserRole UserRole { get; set; }
//this is my many to many prop
public virtual ICollection<Company> Companies { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string CompanyNameHe { get; set; }
public string CompanyNameEn { get; set; }
public string CompanyParent { get; set; }
public DateTime InsertDate { get; set; }
//this is my many to many prop
public virtual ICollection<User> Users { get; set; }
}
/*relationship map*/
public class UsersCompanies
{
public int Id { get; set; }
public int UserId { get; set; }
public int CompanyId { get; set; }
}
//mapping
public class CompanyMap : BaseConfig<Company>
{
public CompanyMap()
{
/*Identity*/
HasKey(c => c.CompanyId);
Property(c => c.CompanyId).HasDatabaseGenerationOption(DatabaseGenerationOption.Identity).HasColumnName("COMPANY_ID");
/*Have default values*/
Property(c => c.InsertDate).HasDatabaseGenerationOption(DatabaseGenerationOption.Computed).HasColumnName("INSERT_DATE");
/*simple scalars*/
Property(c => c.CompanyNameHe).HasMaxLength(32).IsRequired().HasColumnName("COMPANY_NAME_HE");
Property(c => c.CompanyNameEn).HasMaxLength(32).IsRequired().HasColumnName("COMPANY_NAME_EN");
Property(c => c.CompanyParent).HasMaxLength(32).IsRequired().HasColumnName("COMPANY_PARENT");
ToTable("CMS_COMPANY", "GMATEST");
}
}
public class UserMap : BaseConfig<User>
{
public UserMap()
{
/*Identity*/
HasKey(c => c.UserId);
Property(c => c.UserId).HasDatabaseGenerationOption(DatabaseGenerationOption.Identity).HasColumnName("USER_ID");
/*Have default values*/
Property(c => c.InsertDate).HasDatabaseGenerationOption(DatabaseGenerationOption.Computed).HasColumnName("INSERT_DATE");
/*simple scalars*/
Property(c => c.UserName).HasMaxLength(25).IsRequired().HasColumnName("USER_NAME");
Property(c => c.UserPassword).HasMaxLength(25).IsRequired().HasColumnName("USER_PASSWORD");
Property(c => c.UserRoleId).IsRequired().HasColumnName("USER_ROLE_ID");
/*relationship*/
HasRequired(u => u.UserRole).WithMany().HasForeignKey(t => t.UserRoleId);
HasMany(p => p.Companies).WithMany(c => c.Users).Map(mc =>
{
mc.ToTable("UsersCompanies");
mc.MapLeftKey(p => p.UserId, "CompanyId");
mc.MapRightKey(c => c.CompanyId, "UserId");
});
ToTable("CMS_USERS", "GMATEST");
}
}
public class UsersCompaniesMap : BaseConfig<UsersCompanies>
{
public UsersCompaniesMap()
{
/*Identity*/
HasKey(k => k.Id);
Property(c => c.Id).HasDatabaseGenerationOption(DatabaseGenerationOption.Identity).HasColumnName("ID");
Property(c => c.UserId).IsRequired().HasColumnName("USER_ID");
Property(c => c.CompanyId).IsRequired().HasColumnName("COMPANY_ID");
ToTable("CMS_USERS_TO_COMPANIES", "GMATEST");
}
}
Here's the error I get:
'((new
System.Linq.SystemCore_EnumerableDebugView(ctx.FindAll())).Items[0]).Companies'
threw an exception of type
'System.Data.EntityCommandExecutionException'
Inner exception: ORA-00942: table or
view does not exist
You do not really need 3 tables to perform the mapping. You could simply do the following:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Company> Companies { get; set; }
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
And this should do it. As long as you have a virtual ICollection referencing the other entity in both POCO's, CTP5's conventions should take care of everything for you. On the other hand, if you prefer doing it manually using the Fluent API, then check this blog by the ADO.NET team (scroll a little down to the many-to-many relationship section)
The answer for my problem, i have to say many thanks to you all, but Andrey from Devart,
have given me the solution, it's simple.
First off all i have to have, three tables Companies, Users, UsersCompanies/
Second off all i have to map the tables to original names of tables example:
my users table called in Db like that: CMS_USERS i have to map it with original name.
this is the example that i use and it's really works.
HasMany(c => c.Companies)
.WithMany(u => u.Users)
.Map(mc =>
{
mc.ToTable("CMS_USERS_TO_COMPANIES", "GMATEST");
mc.MapLeftKey(c => c.UserId, "USER_ID");
mc.MapRightKey(u => u.CompanyId, "COMPANY_ID");
});
Thank you all.

Automapper newbie question regarding list property

As a new fan of AutoMapper, how would I use it to do the following:
Given the following classes, I want to create FlattenedGroup from Group where the list of item string maps to the title property of Item.
public class Group
{
public string Category { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public int ID { get; set; }
public string Title { get; set; }
}
public class FlattenedGroup
{
public string Category { get; set; }
public IEnumerable<string> Items { get; set; }
}
Thanks
Joseph
The other thing you can do is create a converter from Item -> string:
Mapper.CreateMap<Item, string>().ConvertUsing(item => item.Title);
Now you don't need to do anything special in your Group -> FlattenedGroup map:
Mapper.CreateMap<Group, FlattenedGroup>();
That's all you'd need there.
Give this a try, you can probably use Linq and a lambda expression to map the list of strings in FlattenedGroup with the titles in Group.
Mapper.CreateMap<Group, FlattenedGroup>()
.ForMember(f => f.Category, opt => opt.MapFrom(g => g.Category))
.ForMember(f => f.Items, opt => opt.MapFrom(g => g.Items.Select(d => d.Title).ToList()));
Make sure you add System.Linq to your using statements

Resources