Davood
Davood

Reputation: 5635

How to delete instance using EF?

I created a simple windows console application to test Entity Framework using VS2012 and .NET 4.5.

I added an ADO.NET Entity Data Model to create a model from my database. I use it with this syntax but how can i delete somethings?

static void Main(string[] args)
    {
        using (var ctx = new HKDBEntities())
        {
           int wordId=2;
          var selectedWords = (from o in context.Addresses 
                                where o.word== wordId
                                select o).FirstOrDefault(); 

           //these syntaxt is unavailable why????
           ctx.Words.Delete(word);
           ctx.DeleteObject(word);

          // i test remove method but works not gave me some error
             context.Words.Remove(selectedWords);
        }
    }

How can I use delete syntax?

Upvotes: 0

Views: 153

Answers (2)

Maris
Maris

Reputation: 4776

Use this one : ctx.Words.Remove(word) . And dont forget to SaveChanges(); before disposing context. !!!!!!!I have renewed the answer!!!!!! New idea about this isue:

static void Main(string[] args)
    {
        using (var ctx = new HKDBEntities())
        {
           int wordId=2;
          // This will get the first Addresses which have a `Words` with `WordId`==2
          var selectedWords = ctx.Addresses.First(e=>e.Words.WordId==wordId); 
          //If you want to get to selectedWords the `Words` entity and delete it you should use:
          selectedWords = cts.Words.First(e=>e.WordId == wordId);

          ctx.Words.Remove(selectedWords);
          ctx.SaveChanges();
        }
    }

You was trying to access the remove the data from ctx while you get the data from context

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

You have to use ctx.Words.Remove(word);

Upvotes: 0

Related Questions