简体   繁体   English

在表 'Tickets' 上引入 FOREIGN KEY 约束 'FK_dbo.Tickets_dbo.AspNetUsers_UserID' 可能会导致循环或多个级联路径

[英]Introducing FOREIGN KEY constraint 'FK_dbo.Tickets_dbo.AspNetUsers_UserID' on table 'Tickets' may cause cycles or multiple cascade paths

The Administrator column that you can see from my cshtml page is IssuedTo.您可以从我的 cshtml 页面看到的管理员列是 IssuedTo。 Issue to is linked to id in my AspNetUsers.问题与我的 AspNetUsers 中的 id 相关联。

I'm trying to display the name of what the IssueTo is pointing at so if it's 1 it displays Andy Domagas instead of 1.我正在尝试显示 IssueTo 指向的名称,因此如果它是 1,它会显示 Andy Domagas 而不是 1。

在此处输入图片说明 在此处输入图片说明

I tried to create a virtual ApplicationUser property for IssuedTo like I did with UserID public int UserID { get; set; }我试图为 IssuedTo 创建一个虚拟的 ApplicationUser 属性,就像我对 UserID public int UserID { get; set; }所做的那样public int UserID { get; set; } public int UserID { get; set; } public int UserID { get; set; } and [ForeignKey("UserID")] public virtual ApplicationUser User { get; set; } public int UserID { get; set; }[ForeignKey("UserID")] public virtual ApplicationUser User { get; set; } [ForeignKey("UserID")] public virtual ApplicationUser User { get; set; } [ForeignKey("UserID")] public virtual ApplicationUser User { get; set; } (which allows me to associate User with the property UserID). [ForeignKey("UserID")] public virtual ApplicationUser User { get; set; } (这让我与物业用户名关联用户)。 But when I tried to do it with IssueTo但是当我尝试用 IssueTo 做这件事时

In my Ticket class在我的票务舱

[ForeignKey("IssuedTo")] public virtual ApplicationUser adminAssigned { get; set; }

and in my Ticket\\Index.cshtml并在我的 Ticket\\Index.cshtml

    <th>
        @Html.DisplayNameFor(model => model.adminAssigned)
    </th>

    <td>
        @Html.DisplayFor(modelItem => item.adminAssigned)
    </td>

I get an error saying我收到一条错误消息

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code EntityFramework.dll 中发生了“System.InvalidOperationException”类型的异常,但未在用户代码中处理

Additional information: Unable to complete operation.附加信息:无法完成操作。 The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.提供的 SqlConnection 未指定初始目录或 AttachDBFileName。

pointing to指向

public class TicketController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Ticket
    public ActionResult Index()
    {
        var tickets = db.Tickets.Include(t => t.Category).Include(t => t.User); <---ERROR ON THIS LINE
        return View(tickets.ToList());
    }

Which is weird because my database was working before.这很奇怪,因为我的数据库以前在工作。 So I then specified the databasename by:所以我然后通过以下方式指定了数据库名称:

<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=RecServDatabase;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />

and then I get然后我得到

Unable to update database to match the current model because there are pending changes and automatic migration is disabled.无法更新数据库以匹配当前模型,因为存在未决更改且自动迁移已禁用。 Either write the pending model changes to a code-based migration or enable automatic migration.将挂起的模型更改写入基于代码的迁移或启用自动迁移。 Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.将 DbMigrationsConfiguration.AutomaticMigrationsEnabled 设置为 true 以启用自动迁移。

So I deleted my database and updated it again using update-database所以我删除了我的数据库并使用 update-database 再次更新它

Introducing FOREIGN KEY constraint 'FK_dbo.Tickets_dbo.AspNetUsers_UserID' on table 'Tickets' may cause cycles or multiple cascade paths.在表 'Tickets' 上引入 FOREIGN KEY 约束 'FK_dbo.Tickets_dbo.AspNetUsers_UserID' 可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。 Could not create constraint.无法创建约束。 See previous errors.请参阅以前的错误。

Is it because my ticket table doesn't have AspnetUsers_ID so I need to create a column in it in my Confiuguration.cs file(Seed method)??是不是因为我的票证表没有 AspnetUsers_ID 所以我需要在我的 Configuration.cs 文件(种子方法)中创建一列?

Configuration.cs(Ticket Snippet) Configuration.cs(工单片段)

    var tickets = new List<Ticket>
    {
        new Ticket {
            UserID = users.Single(s => s.LastName == "West").Id, //UserID
            CategoryID = categories.Single(c => c.CategoryName == "Con-X" ).CategoryID,
            Issue = ("Con-X Login Error"),
            Priority = Priority.High
        },
        new Ticket {
            UserID = users.Single(s => s.LastName == "West").Id, //UserID
            CategoryID = categories.Single(c => c.CategoryName == "Desktop" ).CategoryID,
            Issue = ("Can't remote access C0123"),
            Priority = Priority.Med
        },
    };


    foreach (Ticket e in tickets)
    {
        var ticketInDataBase = context.Tickets.Where(
            s =>
                s.User.Id == e.UserID && //UserID
                s.Category.CategoryID == e.CategoryID).SingleOrDefault();
        if (ticketInDataBase == null)
        {
            context.Tickets.Add(e);
        }
    }
    context.SaveChanges();
}

Ticket.cs票务.cs

public class Ticket
{
    public int? TicketID { get; set; }
    public int UserID { get; set; }
    [ForeignKey("UserID")]
    public virtual ApplicationUser User { get; set; }

    [ForeignKey("IssuedTo")]
    public virtual ApplicationUser adminAssigned { get; set; }

}

Update After Suggestion建议后更新

Ticket.cs (Added adminAssigned) Ticket.cs(添加了 adminAssigned)

    public int UserID { get; set; }
    //Added Required
    [Required]
    [ForeignKey("UserID")]
    public virtual ApplicationUser User { get; set; }
    //Added IssueID after update
    public int IssueID{ get; set; }
    //Added Required
    [Required]
    [ForeignKey("IssuedID")]
    public virtual ApplicationUser IssuedUser { get; set; }

IdentityModel.cs(ApplicationUser) (Added TicketsIssuedTo) IdentityModel.cs(ApplicationUser)(添加了 TicketsIssuedTo)

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public async Task<ClaimsIdentity>
        GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
    {
        var userIdentity = await manager
            .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }

    public virtual ICollection<Ticket> Tickets { get; set; }

    public virtual ICollection<ApplicationUser> TicketsIssuedTo { get; set; }    
}

ApplicationDBContext inside IdentityModel.cs (Added OnModelCreating Method) IdentityModel.cs 中的 ApplicationDBContext(添加了 OnModelCreating 方法)

public class ApplicationDbContext
    : IdentityDbContext<ApplicationUser, ApplicationRole, int,
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }


    public DbSet<Ticket> Tickets { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Depot> Depots { get; set; }

}

IdentityModel.cs身份模型.cs

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace RecreationalServicesTicketingSystem.Models
{
    public class ApplicationUserLogin : IdentityUserLogin<int> { }
    public class ApplicationUserClaim : IdentityUserClaim<int> { }
    public class ApplicationUserRole : IdentityUserRole<int> { }

    public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
    {
        public string Description { get; set; }

        public ApplicationRole() : base() { }
        public ApplicationRole(string name)
            : this()
        {
            this.Name = name;
        }

        public ApplicationRole(string name, string description)
            : this(name)
        {
            this.Description = description;
        }
    }

    public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
    {
        public async Task<ClaimsIdentity>
            GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
        {
            var userIdentity = await manager
                .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }

        public bool IsAdministrator { get; set; }
        [StringLength(50, MinimumLength = 1)]

        public string LastName { get; set; }
        [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]

        [Column("FirstName")]
        public string FirstMidName { get; set; }

        public string FullName
        {
            get { return FirstMidName + " " + LastName; }
        }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime EnrollmentDate { get; set; }
        public int DepartmentID { get; set; }
        [ForeignKey("DepartmentID")]
        public virtual Department Department { get; set; }
        public int DepotID { get; set; }
        [ForeignKey("DepotID")]
        public virtual Depot Depot { get; set; }
        public virtual ICollection<Ticket> Tickets { get; set; }
        public virtual ICollection<ApplicationUser> IssuedTo { get; set; }
    }


    public class ApplicationDbContext
        : IdentityDbContext<ApplicationUser, ApplicationRole, int,
        ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        }
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

        static ApplicationDbContext()
        {
            Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
        }


        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }


        public DbSet<Ticket> Tickets { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Depot> Depots { get; set; }

  //      public System.Data.Entity.DbSet<RecreationalServicesTicketingSystem.Models.ApplicationUser> ApplicationUsers { get; set; }
    }



    public class ApplicationUserStore :
    UserStore<ApplicationUser, ApplicationRole, int,
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUserStore<ApplicationUser, int>, IDisposable
    {
        public ApplicationUserStore()
            : this(new IdentityDbContext())
        {
            base.DisposeContext = true;
        }

        public ApplicationUserStore(DbContext context)
            : base(context)
        {
        }
    }


    public class ApplicationRoleStore
    : RoleStore<ApplicationRole, int, ApplicationUserRole>,
    IQueryableRoleStore<ApplicationRole, int>,
    IRoleStore<ApplicationRole, int>, IDisposable
    {
        public ApplicationRoleStore()
            : base(new IdentityDbContext())
        {
            base.DisposeContext = true;
        }

        public ApplicationRoleStore(DbContext context)
            : base(context)
        {
        }




    }



}

Introducing FOREIGN KEY constraint 'FK_dbo.Tickets_dbo.AspNetUsers_UserID' on table 'Tickets' may cause cycles or multiple cascade paths.在表 'Tickets' 上引入 FOREIGN KEY 约束 'FK_dbo.Tickets_dbo.AspNetUsers_UserID' 可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。 Could not create constraint.无法创建约束。 See previous errors.请参阅以前的错误。

The cause of this is that you are mapping two foreign keys to a single table.原因是您将两个外键映射到单个表。

Refer to this answer .参考这个答案 To fix this you should disable the cascade on delete to false on the model builder.要解决此问题,您应该在模型构建器上将删除级联禁用为 false。

This will disable all cascade deletes on your context:这将禁用您上下文中的所有级联删除:

protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

UPDATE:更新:

I noticed you are assigning foreignkey IssuedID but you didn't declare it.我注意到您正在分配外键 IssuedID 但您没有声明它。

public class Ticket
{
    public int? TicketID { get; set; }
    public int UserID { get; set; }
    public int IssuedID { get; set; }

    [ForeignKey("UserID")]
    public virtual ApplicationUser User { get; set; }

    [ForeignKey("IssuedID")]
    public virtual ApplicationUser IssuedUser { get; set; }
}

On your view (Ticket\\Index.cshtml):在您看来(Ticket\\Index.cshtml):

<th>
    @Html.DisplayNameFor(model => model.IssuedUser)
</th>

<td>
    @Html.DisplayFor(modelItem => item.IssuedUser.FullName) // Or something similar
</td>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在表“模型”上引入FOREIGN KEY约束“ FK_dbo.Models_dbo.Makes_MakeId”可能会导致循环或多个级联路径 - Introducing FOREIGN KEY constraint 'FK_dbo.Models_dbo.Makes_MakeId' on table 'Models' may cause cycles or multiple cascade paths 在表 'Jobs' 上引入 FOREIGN KEY 约束 'FK_Jobs_AspNetUsers_UserId' 可能会导致循环或多个级联路径 - Introducing FOREIGN KEY constraint 'FK_Jobs_AspNetUsers_UserId' on table 'Jobs' may cause cycles or multiple cascade paths 在表“ OrderDetails”上引入FOREIGN KEY约束“ FK_dbo.OrderDetails_dbo.Order_OrderId”可能会导致 - Introducing FOREIGN KEY constraint 'FK_dbo.OrderDetails_dbo.Order_OrderId' on table 'OrderDetails' may cause 在表 'XY' 上引入 FOREIGN KEY 约束 'FK_XY' 可能会导致循环或多个级联路径。 指定 ON DELETE NO ACTION - Introducing FOREIGN KEY constraint 'FK_XY' on table 'XY' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION ef核心2-在表&#39;Y&#39;上引入FOREIGN KEY约束&#39;X&#39;可能会导致循环或多个级联路径 - ef core 2 - Introducing FOREIGN KEY constraint 'X' on table 'Y' may cause cycles or multiple cascade paths 在表上引入外键约束可能会导致循环或多个级联路径 - Introducing Foreign key Constraint on table may cause cycles or multiple cascade paths 在表“模型”上引入FOREIGN KEY约束“列”可能会导致循环或多个级联路径 - Introducing FOREIGN KEY constraint 'Column' on table 'Model' may cause cycles or multiple cascade paths 实体框架:在表 '' 上引入 FOREIGN KEY 约束 '' 可能会导致循环或多个级联路径 - Entity Framework: Introducing FOREIGN KEY constraint '' on table '' may cause cycles or multiple cascade paths 表&#39;UsageSummaries&#39;上的多态与引入FOREIGN KEY约束可能会导致循环或多个级联路径 - Polymorphism vs Introducing FOREIGN KEY constraint '' on table 'UsageSummaries' may cause cycles or multiple cascade paths 在表table上引入FOREIGN KEY约束键可能会导致循环或多个级联路径。 指定ON DELETE…错误 - Introducing FOREIGN KEY constraint key on table table may cause cycles or multiple cascade paths. Specify ON DELETE … Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM