2

I decided to play around with the code first option with the EF, however, i've run into a problem regarding multiple foreign keys in a single table.

The error I get is:

The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = FK_dbo.Comments_dbo.Users_UserId ]

I have three tables, User, Post and Comments. Using my limited knowledge in this field, I have created three classes.

User

public class User
{
    [Key]
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public DateTime JoinDate { get; set; }
    public string Password { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }

    public User()
    {
        Posts = new List<Post>();
    }
}

Post

public class Post
{
    [Key]
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime PublishDate { get; set; }
    public int UserId { get; set; }
    public  virtual ICollection<Comment> Comments { get; set; }

    public Post()
    {
        Comments = new List<Comment>();
    }
}

Comment

public class Comment
{
    [Key]
    public int CommentId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime CommentDate { get; set; }
    public int UserId { get; set; }
    public int PostId { get; set; }
}

The relationship between the UserId in the 'User' table, and the UserId in the 'Post' table is fine. However, I run into problems when I wish to create a relationship from the 'Comment' table to the 'Post' and 'User' tables. I'm not sure what i'm doing wrong, as each table is connected to their respective Id. Any help would be appreciated.

4

2 回答 2

2

您可能必须对其中一个或两个关系禁用级联删除,例如 和 的User.Posts关系User.Comments。您必须使用 Fluent API 覆盖OnModelCreating您的派生DbContext

modelBuilder.Entity<User>()
    .HasMany(u => u.Posts)
    .WithRequired()
    .HasForeignKey(p => p.UserId)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<User>()
    .HasMany(u => u.Comments)
    .WithRequired()
    .HasForeignKey(c => c.UserId)
    .WillCascadeOnDelete(false);

或者,您可以将关系设为User可选而不是必需。就像使UserId外键属性可以PostComment空一样简单:

public int? UserId { get; set; }

从业务的角度来看,即使在用户被删除后,允许在系统中保持匿名的帖子和评论也是有意义的,由in和的null值表示。UserIdPostComment

于 2013-05-01T19:12:01.910 回答
0

您需要配置映射:http ://www.remondo.net/code-first-fluent-api-entity-type-configuration/

于 2013-05-01T17:18:37.443 回答