在ASP.NET Core 2.1中,可以使用连接主键进行编辑的常见解决方法是使用Entity Framework Core来处理数据库操作。下面是一个示例,展示了如何使用连接主键进行编辑。
假设有两个实体类:Author
和Book
,它们之间是一对多的关系,即一个作者可以有多本书。
首先,定义实体类:
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public ICollection Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
然后,在DbContext
类中添加实体集和连接主键的配置:
public class ApplicationDbContext : DbContext
{
public DbSet Authors { get; set; }
public DbSet Books { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasOne(b => b.Author)
.WithMany(a => a.Books)
.HasForeignKey(b => b.AuthorId);
}
}
接下来,在控制器中进行编辑操作:
public class AuthorController : Controller
{
private readonly ApplicationDbContext _dbContext;
public AuthorController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public IActionResult Edit(int id)
{
var author = _dbContext.Authors.Include(a => a.Books).FirstOrDefault(a => a.AuthorId == id);
if (author == null)
{
return NotFound();
}
return View(author);
}
[HttpPost]
public IActionResult Edit(Author author)
{
if (ModelState.IsValid)
{
_dbContext.Update(author);
_dbContext.SaveChanges();
return RedirectToAction("Index");
}
return View(author);
}
}
在编辑视图(Edit.cshtml)中,可以使用表单绑定连接主键的相关字段:
@model Author
这样,当提交编辑表单时,连接主键将自动关联和更新相关的实体数据。