简体   繁体   中英

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"

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 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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM