我正在尝试为Index View中的每个Person打印Person.bank1.Name,但始终为NULL。我先使用Code。在数据库表中,一切正常。
上下文是:
public class PersonContext : DbContext
{
public PersonContext()
: base("name=PersonContext")
{
Configuration.ProxyCreationEnabled = true;
Configuration.LazyLoadingEnabled = true;
}
public virtual DbSet<Bank> banks { get; set; }
public virtual DbSet<Person> person { get; set; }
}
人员模型
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int bank { get; set; }
public virtual Bank bank1 { get; set;}
}
银行型号:
public class Bank
{
public int Id {get;set;}
public string Name { get; set; }
public virtual ICollection<Person> person { get; set; }
}
人员控制器索引和创建方法:
public ActionResult Index()
{
var person = db.person.Include(c => c.bank1);
return View(person.ToList());
}
// GET: Persons/Create
public ActionResult Create()
{
ViewBag.BankList = new SelectList(db.banks, "id", "name");
return View();
}
// POST: Persons/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,bank")] Person person)
{
ViewBag.BankList = new SelectList(db.banks, "id", "name");
if (ModelState.IsValid)
{
db.person.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
答案 0 :(得分:0)
在“人员类别”中将银行int财产声明为外键-
[ForeignKey("Bank1")]
public int bank { get; set; }
这应该可以解决问题。