2

我设置了这些模型:

public class Advisor
    {
    public virtual int AdvisorId { get; set; }
    public virtual int UserId { get; set; }
    public User User { get; set; }

    public ICollection<AdvisorStudentMap> AdvisorStudentMaps { get; set; }
    }

public class AdvisorStudentMap
{
    [Required]
    public virtual int AdvisorId { get; set; }
    [Required]
    public virtual int UserId { get; set; }
}

public class User
{
    public virtual int UserId { get; set; }
    public virtual string UserName { get; set; }
    public virtual string FirstName { get; set; }
    public ICollection<AdvisorStudentMap> AdvisorStudentMaps { get; set; }
}

在我的 OnModelCreating 我有:

modelBuilder.Entity<AdvisorStudentMap>()
    .HasKey(t => new {t.AdvisorId, t.UserId});

在我的流利的 api 中,如何设置它,以便当我删除顾问时,它也会删除 AdvisorStudentMap?我不断收到错误消息:表 'AdvisorStudentMaps' 上的 Message=Introducing FOREIGN KEY 约束 'FK_dbo.AdvisorStudentMaps_dbo.Users_UserId' 可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。无法创建约束。请参阅以前的错误。

更新-也在 OnModelCreating 我有:

modelBuilder.Entity<Advisor>()
.HasRequired(t => t.AdvisorStudentMaps).WithMany().WillCascadeOnDelete(true);

有了这个我得到错误'级联外键'FK_dbo.Advisors_dbo.AdvisorStudentMaps_AdvisorId_UserId'不能创建引用列'Advisors.AdvisorId'是一个标识列。

4

2 回答 2

1

您似乎正在尝试模拟学生和顾问之间的多对多关系。这将是您通常这样做的方式:

public class Advisor
 {
    //Key fields don't need to be marked virtual
    public int AdvisorId { get; set; }

    //If you want the property to lazy load then you should mark it virtual
    public virtual ICollection<Student> Students{ get; set; }

    //Advisors have a UserProfile
    public int UserProfileId{get;set;}
    public virtual UserProfile UserProfile {get; set;}    
}

public class Student
{
    public int StudentId { get; set; }
    public virtual ICollection<Advisor> Advisors { get; set; }

    //Students also have a UserProfile
    public int UserProfileId{get;set;}
    public virtual UserProfile UserProfile {get; set;}
}

public class UserProfile
{
   public int UserProfileId{get;set;}

   //NB not marked virtual - that is only needed on navigation properties when 
   //we want to use lazy loading
   public string UserName {get;set}
   public string FirstName {get;set}
}

实体框架会自动创建连接表来对关系建模。除非您需要向关系添加属性,否则您不需要 AdvisorStudentMap 实体。

至于删除问题的级联。如果您删除一个用户,那么这可以级联到学生表和顾问表。从 Student 到 StudentAdvisorMap 有一条级联路径,从 Advisor 到 StudentAdvisorMap 有一条级联路径。因此有多个级联路径。Sql Server 不允许这样做。您必须在代码中显式实现删除以避免这种情况

于 2013-08-20T08:20:55.350 回答
1

我在这个链接的帮助下想出了这个:http: //blog.cdeutsch.com/2011/09/entity-framework-code-first-error-could.html 正如他在博客上所说,它不是很直观但这是使它起作用的语法:

modelBuilder.Entity<AdvisorStudentMap>()
            .HasRequired(u=>u.User)
            .WithMany(m=>m.AdvisorStudentMaps)
            .WillCascadeOnDelete(false);
于 2013-08-22T14:19:44.527 回答