我有3张表如下:
ApplicationUser:
public class ApplicationUser : IdentityUser
{
..some basic properties..
// navigation properties
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Album> Albums { get; set; }
}Post
public class Post
{
public long Id { get; set; }
public string Content { get; set; }
public int? AlbumId { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Album Album { get; set; }
}专辑
public class Album
{
public int Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}最后是ApplicationDbContext
modelBuilder.Entity<ApplicationUser>()
.HasMany(a=>a.Posts)
.WithRequired(a=>a.User)
.HasForeignKey(a=>a.UserId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Post>()
.HasKey(p => p.Id);
modelBuilder.Entity<Album>()
.HasKey(a => a.Id);
modelBuilder.Entity<ApplicationUser>()
.HasMany(u=>u.Albums)
.WithOptional()
.HasForeignKey(a=>a.UserId)
.WillCascadeOnDelete();
modelBuilder.Entity<Album>()
.HasMany(a=>a.Posts)
.WithRequired()
.HasForeignKey(p=>p.AlbumId)
.WillCascadeOnDelete();当我运行迁移和更新数据库时,会得到一个错误:
ALTER语句与外键约束"FK_dbo.Posts_dbo.Albums_AlbumId“冲突。冲突发生在数据库“aspnet 20161012104217”、表"dbo.Albums“、列'Id‘中。
有人能告诉我他们冲突的原因吗?在我看来是很合法的。
发布于 2016-11-13 08:44:12
在您的代码中,您将AlbumId设置为nullable,但在配置定义的WithRequeired()中
public class Post
{
public long Id { get; set; }
public string Content { get; set; }
public int? AlbumId { get; set; } //<-- this one
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Album Album { get; set; }
}
modelBuilder.Entity<Album>()
.HasMany(a=>a.Posts)
.WithRequired() //<-- this one
.HasForeignKey(p=>p.AlbumId)
.WillCascadeOnDelete();如果AlbumId是nullable,则应该更改配置:
//Ef by default conventions set the AlbumId as foreign key
modelBuilder.Entity<Album>()
.HasMany(a=>a.Posts)
.WithOptional(a=>a.Album);如果AlbumId不是nullable,则更改属性:
public class Post
{
public long Id { get; set; }
public string Content { get; set; }
public int AlbumId { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Album Album { get; set; }
}并使用以下配置:
//Ef by default conventions set the AlbumId as foreign key
modelBuilder.Entity<Album>()
.HasMany(a=>a.Posts)
.WithRequired(a=>a.Album)
.WillCascadeOnDelete();https://stackoverflow.com/questions/40571638
复制相似问题