asp.Net 核心 2.0 MVC 问题以编辑/插入问题



我的代码有问题,更可能是理解问题。 我有一个包含足球比赛数据的模型。 这场比分对决有两支球队主场/客场

匹配模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace WebApplication2.Models
{
public class Match
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Anpfiff ist ein Pflichtfeld!")]
public DateTime Anpfiff { get; set; }
[Required(ErrorMessage = "Heim ist ein Pflichtfeld!")]
public Team Heim { get; set; }
[Required(ErrorMessage = "Gast ist ein Pflichtfeld!")]
public Team Gast { get; set; }
public string Ergebnis90 { get; set; }
public string Ergebnis { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
}

团队模型:

using System.ComponentModel.DataAnnotations;
namespace WebApplication2.Models
{
public class Team
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Teamname ist ein Pflichtfeld!")]
public string Name { get; set; }
[Required(ErrorMessage = "ISO ist ein Pflichtfeld!")]
public string Iso { get; set; }
[Required(ErrorMessage = "Gruppe ist ein Pflichtfeld!")]
public string Gruppe { get; set; }
}
}

因此,数据库有一个匹配表,仅包含来自团队的 ID。 但是,如果我尝试在我的视图上只传递模型内的 ID,它不起作用,因为它需要整个团队对象。

基本上我没有id如何创建它,以及我必须在我的控制器和视图中做什么来处理团队。

我希望我能够解释我的观点。

感谢您的帮助 拉斯

添加 id 引用键。

检查此示例:

class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.BlogId)
.HasConstraintName("ForeignKey_Post_Blog");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}

现在,您可以使用 id 执行操作。

最新更新