简体   繁体   中英

C# MVC EF - Set a foreign key to NULL?

I am trying to set a foreign key to "Null".. Using the SQL Management Studio it works fine, but trying it using C#, I am getting a exception:

Exception:

Value cannot be null. Parameter name: entity.

Code:

    var entity = _db.AlleBenutzer.FirstOrDefault(p => p.Id == id);
    if (entity != null)
    {
        var abteilungObjekt = _db.AlleAbteilungen.FirstOrDefault(p => p.Abteilungsname == abteilung);
        var etageObjekt = _db.AlleEtagen.Include(p => p.Abteilung).FirstOrDefault(p => p.Etagenname == etage);
        entity.Abteilung = abteilungObjekt;
        entity.Etage = etageObjekt;
        _db.Entry(entity.Abteilung).State = EntityState.Modified;
        _db.Entry(entity.Etage).State = EntityState.Modified;
        _db.Entry(entity).State = EntityState.Modified;
        _db.SaveChanges();
    }

My both models look like that: (cut some pieces)

public class Benutzer
{
    public int Id { get; set; }
    public Abteilung Abteilung { get; set; }
    public Etage Etage { get; set; }
}

public class Abteilung
{
    public int Id { get; set; }
    public string Abteilungsname { get; set; }
}

Can anyone help me out? How do I modify my model to be able to make my Foreign Keys nullable? Thanks in advance :)

In your model the ID that is acting as your FK should be an int? to make it nullable.

Try:

var entity = _db.AlleBenutzer.FirstOrDefault(p => p.Id == id);
    if (entity != null)
    {
        var abteilungObjekt = _db.AlleAbteilungen.FirstOrDefault(p => p.Abteilungsname == abteilung);
        if (abteilungObjekt != null)
        {
            entity.Abteilung = abteilungObjekt;
            _db.Entry(entity.Abteilung).State = EntityState.Modified;
        }

        var etageObjekt = _db.AlleEtagen.Include(p => p.Abteilung).FirstOrDefault(p => p.Etagenname == etage);
        if (etageObjekt != null)
        {        
            entity.Etage = etageObjekt;
            _db.Entry(entity.Etage).State = EntityState.Modified;
        }

        _db.Entry(entity).State = EntityState.Modified;
        _db.SaveChanges();
    }

As it looks like either abteilungObjekt or etageObjekt may be null when you try to assign them to the entity. You should always perform a null check when using FirstOrDefault() on reference types.

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