[英]How to insert a value into a foreign key in MVC3?
I would like to insert the appropriate value into my foreign key "TennisClubId"... But I have a problem and I catch a "NullReferenceException" 我想在我的外键“ TennisClubId”中插入适当的值...但是我遇到了问题,并且遇到了“ NullReferenceException”
My code : (simplified) 我的代码:(简体)
// POST: /Reservation/Create
[HttpPost]
public ActionResult Create(Reservation createReservation)
{
int id = 0;
var user = User.Identity.Name;
var managers = from c in db.Managers
select c;
foreach (var manager in managers)
{
id = manager.TennisClubID;
}
createReservation.TennisClub.ID = id;// NullReferenceException here (TennisClub.Id is null)
db.Reservations.Add(createReservation);
db.SaveChanges();
}
So, How to insert the appropriate value into a foreign key when I try to create a reservation please ? 因此,当我尝试创建预订时,如何在外键中插入适当的值? Thanks in advance
提前致谢
as you are using Entity-framework
, you will need to create an object map the foreign-key relation, in order to associate it with your main object. 当您使用
Entity-framework
,您需要创建一个对象映射外键关系,以便将其与您的主要对象关联。
Entity-Framework
will (by defualt) provide you will a Collection inside your main object, to reference the one-to-many relation in your table, and this is the key to solve your problem. Entity-Framework
(通过默认)将为您提供主对象内部的Collection,以引用表中的一对多关系,这是解决问题的关键。
consider the following snippet 考虑以下片段
foreach (var manager in managers)
{
var tennisClubToreference = new TennisClub()
{
Id = manager.TennisClubID;
}
manager.TennisClubs.add(tennisClubToreference);
}
sorry for the not well-formatted code, I'm posting from my iphone, forgive me :) 对不起,因为格式不正确,我从iPhone上发帖,请原谅:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.