Fluent NHibernate Mapping multiple tables has relation and joined to each other - fluent-nhibernate

As you see the models have references as one to many. list of project is not mapped here. there are more than one project and the project has more than one role and the role has more than one permission.
error is persister system not avialable.
can anyone look up and help me ?
public class Permission
{
public virtual int MId { get; set; }
public virtual string Id { get; set; }
public virtual bool View { get; set; }
public virtual bool Add { get; set; }
public virtual bool Edit { get; set; }
public virtual bool Delete { get; set; }
public virtual Role Roles { get; set; }
}
public class Role
{
public virtual int RId { get; set; }
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Site_Id { get; set; }
public virtual string Site_Name { get; set; }
public virtual string Domain { get; set; }
public virtual List<Permission> permissions { get; set; }
public virtual Project Project { get; set; }
}
public class Project
{
public virtual int PId { get; set; }
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual List<Role> Roles { get; set; }
}
Mappings
public class PermissionMapping : ClassMap<Permission>
{
public PermissionMapping()
{
Table("ModulePermissions");
Id(u => u.MId).GeneratedBy.Identity();
Map(u => u.Id).Column("ModuleName");
Map(u => u.View);
Map(u => u.Edit);
Map(u => u.Add);
Map(u => u.Delete);
References(x => x.Roles).Column("RolePermissionId");
}
}
public class RoleMapping : ClassMap<Role>
{
public RoleMapping()
{
Table("ModuleRole");
Id(u => u.RId).GeneratedBy.Identity();
Map(u => u.Name);
Map(u => u.Site_Id).Column("SiteId");
Map(u => u.Site_Name).Column("SiteName");
Map(u => u.Domain);
References(x => x.Project).Column("RoleProjectId");
HasMany(u => u.permissions).KeyColumn("RolePermissionId").Inverse().Cascade.All().Not.LazyLoad();
}
}
public class ProjectsMapping : ClassMap<Project>
{
public ProjectsMapping()
{
Table("Projects");
Id(u => u.PId).GeneratedBy.Identity();
Map(u => u.Id).Column("ApiProjectId");
Map(u => u.Name);
HasMany(u => u.Roles).KeyColumn("RoleProjectId").Inverse().Cascade.All().Not.LazyLoad();
}
}

Related

EF Core Fluent API statement as Data Annotation

Can I write this with data annotations in EF Core?
modelBuilder.Entity<DiagramComponent>()
.HasOne(c => c.Compressor)
.WithMany(c => c.Components);
You will have to create one more class:
public class DiagramComponentComponent
{
public int DiagramComponentId { get; set; }
public int ComponentId { get; set; }
[ForeignKey(nameof(DiagramComponentId))]
public virtual DiagramComponent DiagramComponent { get; set; }
[ForeignKey(nameof(ComponentId))]
public virtual Component Component { get; set; }
}
and add attributes to existing classes:
public class DiagramComponent
{
public int CompressorId { get; set; }
[ForeignKey(nameof(CompressorId))]
[InverseProperty("DiagramComponents")]
public virtual Compressor Compressor { get; set; }
[InverseProperty(nameof(DiagramComponentComponent.DiagramComponent))]
public virtual ICollection<DiagramComponentComponent> DiagramComponentComponents { get; set; }
}
public class Compressor
{
[InverseProperty(nameof(DiagramComponent.Compressor))]
public virtual ICollection<DiagramComponent> DiagramComponents { get; set; }
}
public class Component
{
[InverseProperty(nameof(DiagramComponentComponent.Component))]
public virtual ICollection<DiagramComponentComponent> DiagramComponentComponents { get; set; }
}
and add to dbcontext:
modelBuilder.Entity<DiagramComponentComponent>(entity =>
{
entity.HasOne(d => d.DiagramComponent )
.WithMany()
.HasForeignKey(d => d.DiagramComponentId )
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_DiagramComponentComponent_Component_Diagram");
entity.HasOne(d => d.Component)
.WithMany()
.HasForeignKey(d => d.ComponentId )
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_DiagramComponentComponent_Component");
});

Fluent NHibernate - 1:1 Relationship with Nullable Field

Given the following model, I want to be able to enter a new WriteOffApprovalUser and have the Employee field be null. This is a 1:1 or null relationship.
public class WriteOffApprovalUser
{
public virtual string UserName { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee
{
public virtual string EmployeeID { get; set; }
public virtual string EmployeeStatusCode { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string JobTitle { get; set; }
public virtual string Division { get; set; }
public virtual string Department { get; set; }
public virtual string Location { get; set; }
public virtual string City { get; set; }
public virtual string DeskLocation { get; set; }
public virtual string MailID { get; set; }
public virtual string Phone { get; set; }
public virtual string PreferredName { get; set; }
public virtual string Fax { get; set; }
public virtual string SecCode { get; set; }
public virtual string SupervisorID { get; set; }
public virtual string UserId { get; set; }
}
Class Maps
public class WriteOffApprovalUserMap : ClassMap<WriteOffApprovalUser>
{
public WriteOffApprovalUserMap()
{
Table("WRITEOFF_APPROVAL_USER");
Id(x => x.UserName).Column("USER_NAME");
//Map(x => x.Employee).Nullable();
HasOne(x => x.Employee)
.Class<Employee>()
.Constrained()
.Cascade.SaveUpdate()
.PropertyRef("UserId");
}
}
public class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Table("ADP_EMPLOYEE");
Id(x => x.EmployeeID).Column("EMPLID").GeneratedBy.Native("");
Map(x => x.FirstName).Column("FIRST_NAME");
Map(x => x.LastName).Column("LAST_NAME");
Map(x => x.PreferredName).Column("PREFERRED_NAME");
Map(x => x.UserId).Column("USER_ID");
}
}
Query/Save
using (var session = SessionProvider.GetSession())
{
using (var tx = session.BeginTransaction())
{
var user = new WriteOffApprovalUser() { UserName = "SAMSTR" };
session.Save(user);
tx.Commit();
}
}
This complains that Employee is null. How do I specify that Employee can be null?
Also, do all Id fields have to be integral? A lot of the keys on our tables are strings.
First off all if you put it as 1:1 it shouldn't be NULL because it's not correct design.
But here is an example of how to do so:
1) One way
HasOne(x => x.Employee)
.Class<Employee>().Nullable().NotFound.Ignore().PropertyRef("UserId");
2) Second way
References(x => x.Category).Column("UserId").Nullable().NotFound.Ignore();

Delete on Many to Many Relationship using Fluent Nhibernate

User Class
public class User
{
public virtual Guid UserID { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual string FullName { get; set; }
public virtual string Email { get; set; }
public virtual TimeSpan LastLogin { get; set; }
public virtual bool IsActive { get; set; }
public virtual DateTime CreationDate { get; set; }
public virtual IList<Role> Roles { get; set; }
public User()
{
Roles = new List<Role>();
}
public virtual void AddRoles(Role role)
{
role.Users.Add(this);
Roles.Add(role);
}
}
Role Class
public class Role
{
public virtual int? RoleID { get; set; }
public virtual string RoleName { get; set; }
public virtual bool IsActive { get; set; }
public virtual string Description { get; set; }
public virtual IList<User> Users { get; set; }
public virtual IList<Role> Roles { get; set; }
public Role()
{
Users = new List<User>();
}
}
UserMap Class
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("tblUsers");
Id(user => user.UserID).GeneratedBy.Guid();
Map(user => user.UserName).Not.Nullable();
Map(user => user.Password).Not.Nullable();
Map(user => user.FullName).Not.Nullable();
Map(user => user.Email).Not.Nullable();
//Map(user => user.LastLogin).Nullable();
Map(user => user.IsActive).Not.Nullable();
Map(user => user.CreationDate).Not.Nullable();
HasManyToMany<Role>(x => x.Roles).Table("tblUserInRoles")
.ParentKeyColumn("UserID")
.ChildKeyColumn("RoleID")
.Cascade.All()
//.AsSet()
//.Inverse()
.Not.LazyLoad();
}
}
RoleMap Class
public class RoleMap : ClassMap<Role>
{
public RoleMap()
{
Table("tblRoles");
Id(role => role.RoleID).GeneratedBy.Identity();
Map(role => role.RoleName).Not.Nullable();
Map(role => role.IsActive).Not.Nullable();
Map(role => role.Description).Not.Nullable();
HasManyToMany<User>(x => x.Users)
.Table("tblUserInRoles")
.ParentKeyColumn("RoleID")
.ChildKeyColumn("UserID")
.Cascade.All()
.Inverse()
.Not.LazyLoad();
}
}
My questions are:
I want to delete all roles of particular user? [Answered by danyolgiax]
Get roles of user
Can Any one guide me..
try .Inverse() on User (not on Role) and then:
user.Roles.Clear();
yourNhSession.SaveOrUpdate(user);
update
User user= yourNhSession.Get<User>(userId);
IList<Role> role= user.Roles;

Nhibernate Mapping relationships on multiple columns

I'm having problems mapping a relationaship between two entities when there are two columns involved in the mapping.
I'm modelling a state machine with two object types - State and Transition. Each process has its own state machine, so States and Transitions need to be identified by ProcessId. My entity classes are like this:
public class State
{
public virtual long Id { get; set; }
public virtual int ProcessId { get; set; }
public virtual int Ordinal { get; set; }
public virtual Process Process { get; set; }
public virtual ICollection<Transition> TransitionsIn { get; set; }
public virtual ICollection<Transition> TransitionsOut { get; set; }
}
public class Transition
{
public virtual long Id { get; set; }
public virtual long ProcessId { get; set; }
public virtual int FromStateNum { get; set; }
public virtual int ToStateNum { get; set; }
public virtual long StateActionId { get; set; }
public virtual Process Process { get; set; }
public virtual StateAction StateAction { get; set; }
public virtual State FromState { get; set; }
public virtual State ToState { get; set; }
}
I need the navigation properties (State.TransitionsIn, State.TransitionsOut, Transition.FromState, Transition.ToState) to be based on the ProcessId and the Ordinal number of the state. For example, Transition.FromState should navigate to the entity where t.ProcessId = s.ProcessId and t.FromStateNum = s.Ordinal.
I've tried the following mapping, but it complains that I'm using two columns to map to one (StateId).
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumns.Add("ProcessId", "ToStateNum")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumns.Add("ProcessId", "FromStateNum")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "Ordinal");
References(t => t.ToState)
.Columns("ProcessId", "Ordinal");
}
}
How can I get this to work?
How about this mapping.. I have not tested it but just trying to give a direction.
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumn("ProcessId")
.KeyColumn("ToStateNum").PropertyRef("Ordinal")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumn("ProcessId")
.KeyColumn("FromStateNum").PropertyRef("Ordinal")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "FromStateNum");
References(t => t.ToState)
.Columns("ProcessId", "ToStateNum");
}
}

How am I supposed to query for a persisted object's property's subproperty in nhibernate?

I'm feeling dumb.
public class Uber
{
public Foo Foo { get; set; }
public Bar Bar { get; set; }
}
public class Foo
{
public string Name { get; set; }
}
...
var ubercharged = session.CreateCriteria(typeof(Uber))
.Add(Expression.Eq("Foo.Name", "somename"))
.UniqueResult<Uber>();
return ubercharged;
This throws a "could not resolve property" error.
What am I doing wrong? I want to query for an Uber object that has a property Foo which has a Name of "somename".
updated with real life example, repository call, using fluent nhibernate:
public UserPersonalization GetUserPersonalization(string username)
{
ISession session = _sessionSource.GetSession();
var personuser = session.CreateCriteria(typeof(UserPersonalization))
.Add(Expression.Eq("User.Username", username))
.UniqueResult<UserPersonalization>();
return personuser;
}
The classes/mappings:
public class User
{
public virtual Guid UserId { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string PasswordSalt { get; set; }
public virtual bool IsLockedOut { get; set; }
public virtual bool IsApproved { get; set; }
}
public class Person
{
public virtual int PersonId { get; set; }
public virtual string Name { get; set; }
public virtual Company Company { get; set; }
}
public class UserPersonalization
{
public virtual int UserPersonalizationId { get; set; }
public virtual Person Person { get; set; }
public virtual User User { get; set; }
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.UserId).GeneratedBy.Guid().ColumnName("UserId");
Map(x => x.Username);
Map(x => x.PasswordHash);
Map(x => x.PasswordSalt);
Map(x => x.Email);
Map(x => x.IsApproved);
Map(x => x.IsLockedOut);
}
}
public class UserPersonalizationMap : ClassMap<UserPersonalization>
{
public UserPersonalizationMap()
{
WithTable("UserPersonalization");
Id(x => x.UserPersonalizationId).ColumnName("UserPersonalizationId");
References(x => x.Person).ColumnName("PersonId");
References(x => x.User).ColumnName("UserId");
}
}
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Id(x => x.PersonId).ColumnName("PersonId");
Map(x => x.Name);
References(x => x.Company).ColumnName("CompanyId");
}
}
Try this:
var ubercharged = session.CreateCriteria(typeof(Uber))
.CreateCriteria("Foo")
.Add(Restrictions.Eq("Name", "somename"))
.UniqueResult<Uber>();
Can you sort using "ubercharged.AddOrder(Order.asc("Foo.Name")) syntax? This syntax should work in NHib 2.01. If not, your maps are not working correctly.
Stuart's answer should work fine for you though.