2
votes

Below are my domain entities

public class User
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string EmailAddress { get; set; }

    public RoleType RoleType { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string Name { get; set; }
}

I have made RoleType as a complex type (to acheive enum mapping). So I could use something like context.Users.FirstOrDefault(u => u.RoleType.Value == (long)RoleTypes.Admin) RoleTypes.Admin is an enum mapping to the Role entity

public class RoleType
{
    public int Value { get; set; }

    // And all the implicit operators to map with enum
}

And then I have created a mapping using fluent api

public class RoleTypeMapping : ComplexTypeConfiguration<RoleType>
{
    public RoleTypeMapping()
    {
        Property(r => r.Value)
            .HasColumnName("RoleId"); // To make sure that in RoleType property of User EF entity maps to an int column [RoleId] in database (table [Users])
    }
}

Using fluent-api, I want to create a foreign key association in [Users] table for [Users].[RoleId] referencing [Role].[Id]. Please can anyone provide me guidance to acheive this

I tired adding a property of type Role and creating a mapping through fluent-api, but EF creates another column Role_Id and makes it the foreign key. I want the existing [RoleId] column (complex type) to be the foreign key

1

1 Answers

3
votes

It is not possible. If you want to have association with Role table you must abandon your enum-like approach and define Users entity like:

public class User
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string EmailAddress { get; set; }

    public Role Role { get; set; }
}

First of all relations are not enums and complex types cannot contain navigation properties (as well as foreign keys).