Assigning UserId to Foreign Key = null

Springbokkie

I'm using Entity Framework 5 and MVC 4, with .NET 4.5 using Code First migrations. I have foreign keys between two entities in a 1 to zero-or-1 relationship. When I try to create the record for Jogger everything blows up. I get error messages that are either:

  • Foreign Key is a null reference
  • dbo.Jogger does not exist
  • Unhandled exception ... no metadata.

When I run the EF Viewer the navigation relationships are perfect. No Fluent API code is used at the moment.

User Class

     [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

    // Other properties

    public int? JoggerId { get; set; }
    public virtual Jogger Jogger { get; set; }

Jogger Class

    [ForeignKey("UserId")]
    public int JoggerId { get; set; }

    public virtual UserProfile UserId { get; set; }

When the JoggerController is generated it produces this code for the Get and Post Methods:

// GET: /Jogger/Create

    public ActionResult Create()
    {
        ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName");
        return View();
    }

    //
    // POST: /Jogger/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Jogger jogger)
    {



        if (ModelState.IsValid)
        {
            db.Jogger.Add(jogger);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName", jogger.JoggerId);
        return View(jogger);
    }

In the Jogger/Create view there are no fields for JoggerId or UserId according to the generated code.

Typically it fails on the (ModelState.IsValid) portion of code where the Output shows JoggerId = 0 and UserId = null.

I have not seen this behaviour on the Contoso University tutorial on asp.net's website and I have looked at the MSDN Learn EF site as well. I can't seem to solve this problem. Your advice is appreciated.

Springbokkie

After much trial and error I found a way that works to assign the Foreign Key a value.

Firstly, my relationships were setup incorrectly: UserProfile Class did not need the public int? GolferId to represent a navigation property. Final classes looked as follows:

UserProfile

  [Key]
  [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
  public int UserId { get; set; }
  public string UserName { get; set; }

  // Navigation properties
  public virtual Jogger Jogger { get; set; }

Jogger Class

[Key] 
[ForeignKey("UserId")]
public int JoggerId { get; set; }

public string Pronation {get; set;}

public virtual UserProfile UserId { get; set; }

This setup the correct relationship without needing any Fluent API code.

To assign the ForeignKey value was a little trickier and I'm sure there are MUCH better ways of doing it than this.

  1. Instead of the other scaffolding method of defining (id = 0), I used a FormCollection. You can also use the [Bind(Include = "field1, field2, field3")] to ensure that the correct fields are being posted.
  2. There's a long way of getting to the logged-in User's UserId which takes advantage of User.Identity.Name
  3. The FormCollection allows me to reference and save the other fields e.g. Pronation

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(FormCollection values)
    {
    
        var jogger = new Jogger();
        TryUpdateModel(jogger);
    
        var context = new TestContext();
        var userqq = User.Identity.Name;
        var user = context.UserProfiles.SingleOrDefault(u => u.UserName == userqq);
    
        if (ModelState.IsValid)
        {
    
                jogger.JoggerId = user.UserId;
                jogger.Pronation = values["Pronation"];
    
    
                db.Joggers.Add(jogger);
                db.SaveChanges();
               return View();
    
    
        }
            ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName", jogger.JoggerId);
            return View(jogger);
    
    }
    

This wasn't pretty at all but it does work. Thanks to @Moeri for pointing me in the right direction.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to solve "wl_deviceNoProvisioningRealm. null returned for key: userId" error?

From Dev

Hibernate is inserting null values in foreign key field

From Dev

yii null foreign key

From Dev

Hibernate Many to one updating foreign key to null

From Dev

PostgreSQL: NULL value in foreign key column

From Dev

A conditional JOIN depending on whether the foreign key is NULL?

From Dev

Join two DataTables even if foreign key is NULL

From Dev

Foreign Key Reference Already Has Value Exception Linq to SQL When Assigning Null

From Dev

DataContext always returns null as foreign key

From Dev

Foreign key is allowed to be NULL?

From Dev

FirstOrDefault returns null on foreign key

From Dev

EF Navigation Property with null foreign key

From Dev

Assigning Foreign Key through PDO SQL

From Dev

Laravel relationship null foreign key fetching

From Dev

If a primary key is NOT NULL, then should a foreign key that references it be specified also as NOT NULL?

From Dev

MySQL Can Foreign Key Be Null

From Dev

JPA foreign key is null in the child table

From Dev

foreign key always stays null

From Dev

mongodb belongsTo Foreign key is null

From Dev

Foreign Key Reference Already Has Value Exception Linq to SQL When Assigning Null

From Dev

Unable to associate models without manually assigning the foreign key in Laravel 5

From Dev

Assigning Foreign Key through PDO SQL

From Dev

Laravel Foreign Key can not be null

From Dev

foreign key always stays null

From Dev

SQL foreign key returns NULL

From Dev

Tastypie foreign key set null

From Dev

mvc 5 code first userid as a Foreign Key - How to save data

From Dev

Update of the foreign key to a null value

From Dev

Cannot insert duplicate key when directly assigning Foreign Key with EF

Related Related

  1. 1

    How to solve "wl_deviceNoProvisioningRealm. null returned for key: userId" error?

  2. 2

    Hibernate is inserting null values in foreign key field

  3. 3

    yii null foreign key

  4. 4

    Hibernate Many to one updating foreign key to null

  5. 5

    PostgreSQL: NULL value in foreign key column

  6. 6

    A conditional JOIN depending on whether the foreign key is NULL?

  7. 7

    Join two DataTables even if foreign key is NULL

  8. 8

    Foreign Key Reference Already Has Value Exception Linq to SQL When Assigning Null

  9. 9

    DataContext always returns null as foreign key

  10. 10

    Foreign key is allowed to be NULL?

  11. 11

    FirstOrDefault returns null on foreign key

  12. 12

    EF Navigation Property with null foreign key

  13. 13

    Assigning Foreign Key through PDO SQL

  14. 14

    Laravel relationship null foreign key fetching

  15. 15

    If a primary key is NOT NULL, then should a foreign key that references it be specified also as NOT NULL?

  16. 16

    MySQL Can Foreign Key Be Null

  17. 17

    JPA foreign key is null in the child table

  18. 18

    foreign key always stays null

  19. 19

    mongodb belongsTo Foreign key is null

  20. 20

    Foreign Key Reference Already Has Value Exception Linq to SQL When Assigning Null

  21. 21

    Unable to associate models without manually assigning the foreign key in Laravel 5

  22. 22

    Assigning Foreign Key through PDO SQL

  23. 23

    Laravel Foreign Key can not be null

  24. 24

    foreign key always stays null

  25. 25

    SQL foreign key returns NULL

  26. 26

    Tastypie foreign key set null

  27. 27

    mvc 5 code first userid as a Foreign Key - How to save data

  28. 28

    Update of the foreign key to a null value

  29. 29

    Cannot insert duplicate key when directly assigning Foreign Key with EF

HotTag

Archive