代码优先,模型如下图:
public class Post
{
public int Id { get; set; }
public string title { get; set; }
public int fid { get; set; }
public int uid { get; set; }
public virtual lnk lnk { get; set; }
public virtual user user { get; set; }
public virtual ICollection<img> imgs { get; set; }
}
public class lnk
{
public int Id { get; set; }
public string lnkman { get; set; }
}
public class model1:Post
{
public string content { get; set; }
}
public class user
{
public int uid { get;set; }
public string Name {get;set;}
public virtual ICollection<Post> posts { get; set; }
}
public class img
{
public int id { get; set; }
public string imgUrl { get; set; }
public int pid { get; set; }
public virtual Post post { get; set; }
}
public class PostContext : DbContext
{
public DbSet<Post> posts { get; set; }
public DbSet<user> users { get; set; }
public DbSet<img> imgs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>().HasKey(i=>i.Id);
modelBuilder.Entity<lnk>().HasKey(i => i.Id);
modelBuilder.Entity<Post>().HasRequired(i => i.lnk).WithRequiredPrincipal();
modelBuilder.Entity<Post>().ToTable("Post");
modelBuilder.Entity<lnk>().ToTable("Post");
modelBuilder.Entity<model1>().ToTable("model1");
modelBuilder.Entity<user>().HasKey(i => i.uid).ToTable("user");
modelBuilder.Entity<user>().HasMany(i => i.posts)
.WithRequired(i => i.user)
.HasForeignKey(i =>i.uid).WillCascadeOnDelete(false);
modelBuilder.Entity<img>().HasKey(i => i.id).ToTable("img");
modelBuilder.Entity<Post>().HasMany(i => i.imgs)
.WithRequired(i => i.post)
.HasForeignKey(i => i.pid)
.WillCascadeOnDelete(false);
}
}
add 和 list 方法运行良好。但是像这样的delele:
using (var db = new PostContext())
{
//model1 ToDel = new model1{ Id=id };
//b.Entry(ToDel).State = System.Data.EntityState.Deleted;
var ToDel = db.users.Single(i => i.uid == id);
db.users.Remove(ToDel);
db.SaveChanges();
return id + "DE: well done!" ;
}
System.Data.SqlClient.SqlException: DELETE statement with REFERENCE constraint "FK_dbo.Post_dbo.user_uid" 冲突。冲突发生在数据库 "jefunfl",表 "dbo.Post",列 'uid'
我想删除带有用户帖子的用户,以及带有帖子 imgs 的帖子。我怎样才能做到这一点?有人可以提供任何提示吗?
顺便说一句,我的中文英语可能很有趣。对不起。这是我的第一篇文章,但我不是新人。谢谢