0
votes

I'm trying to create database relationship between two tables.

I have redemption codes which can be free. But one user has only one redem code.

I created two entities:

public class UserProfile
{
    [Key]
    [ForeignKey("User")]
    public int Id { get; set; }

    //... other fields

    public virtual RedemptionCode RedemptionCode { get; set; }

    public virtual User User { get; set; }
}

public class RedemptionCode
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [ForeignKey("UserProfile")]
    public int? UserProfileId { get; set; }
    public virtual UserProfile UserProfile { get; set; }

    [Required]
    public string Code { get; set; }
}

But when I adding a migration I have the following error:

One or more validation errors were detected during model generation:

RedemptionCode_UserProfile_Source: : Multiplicity is not valid in Role 'RedemptionCode_UserProfile_Source' in relationship 'RedemptionCode_UserProfile'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

What do I really want? I want to store free redem codes in db and link one of them with new user in my system.

1
If it's nullable, it cannot be a primary key ..... - marc_s
@marc_s it is my misprint. I mean foreign key of course. - user3818229
can you show the User model's code also? - Sampath

1 Answers

0
votes

Here is the right code for the UserProfile class

public class RedemptionCode
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key,ForeignKey("UserProfile")]
    public int Id { get; set; }

    public int? UserProfileId { get; set; }

    [ForeignKey("UserProfile")]
    public virtual UserProfile UserProfile { get; set; }

    [Required]
    public string Code { get; set; }
}

You have to move the ForeignKey from the property UserProfileId to the navigation property UserProfile and indicate that UserProfile is the principal in the relationship by adding the ForeignKey attribute to the Id of the RedemptionCode class