0

In my business model I have "User Role" entity and one (or zero) "RoleFunctionality" entity assigned to it:

"UserRole"
(
  id integer NOT NULL,
  name character varying(255),
  CONSTRAINT "UserRole_pkey" PRIMARY KEY (id)
)

"RoleFunctionality"
(
  roleid integer NOT NULL,
  functionalities character varying(255) NOT NULL,
  CONSTRAINT fk1 FOREIGN KEY (roleid)
      REFERENCES "UserRole" (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

I would like to have them as One-To-OneOrZero relation. My entities and mappings are below:

public class UserRole
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual RoleFunctionality Functionalities { get; set; }
}

public class UserRoleMap : ClassMap<UserRole>
{
    UserRoleMap()
    {
        Id(x => x.Id).GeneratedBy.Native();
        Map(x => x.Name);
        HasOne(x => x.Functionalities);
    }
}

public class RoleFunctionality
{
    public virtual int RoleId { get; set; }
    public virtual UserRole Role { get; set; }
    public virtual string Functionalities { get; set; }
}

public class RoleFunctionalityMap : ClassMap<RoleFunctionality>
{
    RoleFunctionalityMap()
    {
        Id(x => x.RoleId);
        Map(x => x.Functionalities);
        HasOne(x => x.Role).Constrained().ForeignKey("fk1");
    }
}

Everythings works fine when there is "RoleFunctionality" exists for a "UserRole" - SaveOrUpdate() on works nice.

But I have exception when I would like to delete "UserRole" with "RoleFunctionality" or when I'd like to update "UserRole" with new "RoleFunctionalities" that was null before.

Where is the problem? Thanks in advance.

  • can you share the exception with us? – Mert May 28 '15 at 16:33
  • *If a bit possible, I would suggest - to make your life later easier - to try to convert that into many-to-one. The biggest issue with one-to-one from my perspective is - it is always loading both. Play with.. but try to think about that* – Radim Köhler May 29 '15 at 06:06

1 Answers1

0

After reading some additional information I have made my mappings and entities like below. Works nice now:

public class RoleFunctionalityMap : ClassMap<RoleFunctionality>
{
    RoleFunctionalityMap()
    {
        Id(x => x.RoleId).GeneratedBy.Foreign("Role");
        Map(x => x.Functionalities);
        HasOne(x => x.Role).Constrained();
    }
}

public class RoleFunctionality
{
    public virtual int RoleId { get; set; }
    public virtual string Functionalities { get; set; }
    public virtual UserRole Role { get; set; }
}

public class UserRoleMap : ClassMap<UserRole>
{
    UserRoleMap()
    {
        Id(x => x.Id).GeneratedBy.Native();
        Map(x => x.Name);
        HasOne(x => x.Functionalities).Cascade.All();
    }
}

public class UserRole
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual RoleFunctionality Functionalities { get; set; }
}