从模型生成数据库时出现多重错误?

时间:2011-05-07 17:49:53

标签: mapping entity-framework-4.1

有3个班级:

     public class User
    {
        public Guid Id { get; set; }
        public string Username { get; set; }
        public string PersonelNumber { get; set; }
        public string Password { get; set; }
        public bool IsActive { get; set; }
        public DateTime LastLoginDate { get; set; }
        public bool IsOnline { get; set; }
    }

    public class Comment
    {
        public Guid Id { get; set; }

        /// <summary>
        /// Title of the comment
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Full text for comment
        /// </summary>
        public string Text { get; set; }

        //Maps to the User Id
        public Guid CreatedById { get; set; }

        public virtual User CreatedBy { get; set; }
    }

    public class FileVersion 
    {
        public Guid Id { get; set; }
        public string Path { get; set; }
        public int Version { get; set; }

//Referecne to optional comment        
        public virtual Guid ChangeCommentId { get; set; }
        public virtual Comment ChangeComment { get; set; }
//Referece to user who added a file
        public virtual Guid AddedById { get; set; }
        public virtual User AdddedBy { get; set; }
//Reference to User who may have the file checked out
        public virtual Guid CheckedOutById { get; set; }
        public virtual User CheckedOutBy { get; set; }
}

当数据库尝试在FilVersion和Comment之间创建Comment关系时,我收到错误。我确实为FileVersion类创建了这个映射:

HasOptional(f => f.ChangeComment).WithMany().HasForeignKey(f => f.ChangeCommentId).WillCascadeOnDelete(false);

我不确定如何设置映射,以便在创建数据库时不会出现Multiplicity错误。 FileVersion需要引用谁添加文件以及谁可以将其签出以进行编辑。

1 个答案:

答案 0 :(得分:0)

问题是当外键不接受null时,您无法将Comment定义为可选。将您的实体修改为:

public class FileVersion 
{
    ...     
    public virtual Guid? ChangeCommentId { get; set; }
    public virtual Comment ChangeComment { get; set; }
    ...      
}

或将您的地图修改为:

modelBuilder.Entity<FileVersion>()
            .HasRequired(f => f.ChangeComment)
            .WithMany()
            .HasForeignKey(f => f.ChangeCommentId)
            .WillCascadeOnDelete(false);

CheckedOutBy

可能需要相同