0

I have 2 entities that needs FK on one another:

public class MessagesGroup
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long GroupId { get; set; }

    public string Title { get; set; }
    public DateTime Created { get; set; }
    public int? LastMessageId { get; set; }

    [Required]
    [ForeignKey("GroupId,LastMessageId")]
    public virtual Messages Message { get; set; }
}

public class Messages
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long GroupId { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int MessagesId { get; set; }

    public int UserId { get; set; }

    [StringLength(2000)]
    public string Text { get; set; }

    public DateTime Date { get; set; }

    [StringLength(255)]
    public string AttachmentUrl { get; set; }

    [Required]
    [ForeignKey("GroupId")]
    public virtual MessagesGroup MessageGroup { get; set; }

    [Required]
    [ForeignKey("GroupId,UserId")]
    public virtual MessagesGroupUsers MessagesGroupUsers { get; set; }
}

How to get FK on both entities, because now I am getting error

Unable to determine the principal end of an association between the types 'MDC.Repository.Model.Messages' and 'MDC.Repository.Model.MessagesGroup'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.` and I tried other solutions, nothing helped, only new errors appeared.

EDIT

I tried that solution

public class MessagesGroup
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long GroupId { get; set; }

    public int? LastMessageId { get; set; }

    public virtual Messages Message { get; set; }
}

public class Messages
{
    [Key]
    [Column(Order = 0)]
    [ForeignKey("MessageGroup")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long GroupId { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int MessagesId { get; set; }

    public int UserId { get; set; }

    [Required]
    public virtual MessagesGroup MessageGroup { get; set; }

    [Required]
    [ForeignKey("GroupId,UserId")]
    public virtual MessagesGroupUsers MessagesGroupUsers { get; set; }
}

And now I get

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

And by looking on this new message I get feeling that he can't map on msgGroupId but I can't figure out why.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Serlok
  • 432
  • 1
  • 10
  • 24

0 Answers0