1

I've got following problem. If I'm inserting a record to my database tables with dbcontext each time a new record gets created. So for example if Stadt and Postleitzahl are already existing in table my application should take the Id property of the record insteat of creating a new auto generated Id with same Postleitzahl and Stadt values. Where am I going wrong? My Create Method in Controller looks like this:

public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(CreateKundeViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            var kunde = new Kunde()
            {
                Vorname = viewModel.Vorname,
                Nachname = viewModel.Nachname,
                Strasse = viewModel.Strasse,
                Hausnummer = viewModel.Hausnummer,
                Email = viewModel.Email,
                Telefon = viewModel.Telefon,
                AGB = viewModel.AGB,
                Whatsapp = viewModel.Whatsapp,
                Web = viewModel.Web,
                Aktiv = viewModel.Aktiv
            };

            var anrede = new Anrede()
            {
                AnredeText = viewModel.Anrede,
                AnredeTyp = 1
            };


            var stadt = new Stadt()
            { 
                Ort = viewModel.Ort,
                Postleitzahl = viewModel.Postleitzahl
            };

            var hund = new Hund()
            {
                Name = viewModel.HundName,
                Groesse = viewModel.Groesse,
                Gewicht = viewModel.Gewicht,
                Geburtsdatum = viewModel.Geburtsdatum

            };

            var rasse = new Rasse()
            {
                Rassename = viewModel.Rassename
            };

            var kastriert = new Kastriert()
            {
                Kastrierttyp = viewModel.Kastriertname
            };

            var geschlecht = new Geschlecht()
            {
                Geschlechtstyp = viewModel.Geschlecht
            };

            _context.Anredes.Add(anrede);
             _context.Stadts.Add(stadt);
             _context.Kundes.Add(kunde);
             _context.Rasses.Add(rasse);
             _context.Kastrierts.Add(kastriert);
             _context.Geschlechts.Add(geschlecht);
             _context.Hunds.Add(hund);
            _context.SaveChanges();
        }

        return RedirectToAction("Index", "Kunde");
    }
Daniel3011
  • 17
  • 4

2 Answers2

0

You can check if the record already exsits and then add it, like this:

if(_context.Kundes.Count(e => e.Vorname== kunde.Vorname)==0)
{
 _context.Kundes.Add(kunde);
}
Ehsan Kiani
  • 3,050
  • 1
  • 17
  • 19
  • When I'm using this I'm getting an exepction error, when the record already exists. How can I tell Entity Framework only to insert the value if it's not existing otherwise use the existing value? – Daniel3011 Mar 16 '19 at 17:13
  • Can you tell what the exception message is? – Ehsan Kiani Mar 17 '19 at 04:44
  • I unfortunally cannot add a screenshot as a commet but i'm getting the message "SQL Exeption the INSERT Statement detected a conflict with foreign key "FK_dbo.Kundes_dbo.Stadts.Stadt_Id. Th conflict was detected in database table dbo.Stadts" if the Ort or Postleitzahl (ZIPCode) already exists in the database. – Daniel3011 Mar 17 '19 at 08:26
  • The problem is in the values you're trying to add maybe this link helps https://stackoverflow.com/questions/2965837/insert-statement-conflicted-with-the-foreign-key-constraint-sql-server – Ehsan Kiani Mar 17 '19 at 08:45
-1

If you are using EntityFramework 4.3, you can use AddOrUpdate method, which is under System.Data.Entity.Migrations namespace.

public static void AddOrUpdate<TEntity>(
    this IDbSet<TEntity> set,
    params TEntity[] entities
)
where TEntity : class

Please use the link for reference

If you are using older version of Entity Framework, this link may helps

Update Row if it Exists Else Insert Logic with Entity Framework

Cinchoo
  • 6,088
  • 2
  • 19
  • 34
  • Thanks for your response! How do I have to use it? Is TEntity the place holder for my dbcontext? – Daniel3011 Mar 16 '19 at 17:12
  • May be this article will help http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/ – Cinchoo Mar 16 '19 at 20:11
  • Like it is mentioned in the link, this method should not be used in the code. It is only to be used while seeding in code first approach. @RajN – prinkpan Mar 17 '19 at 17:35