Tom
Tom

Reputation: 1334

Entity Framework won't add object

In the following code, I have a WCF service with a method for adding a tag to a film. In the database, there are three tables: one for tags; one for films; one for joining films and tags via a relationship.

For some reason the following code, specifically the first segment of the if..then..else statement, is not adding a new tag into the table. It isn't throwing any exceptions, it just doesn't seem to be adding anything

    public void AddFilmTag(string tagWordIn, int filmIdIn)
    {
        if (context.Tags.SingleOrDefault(x => x.tagWord == tagWordIn) == null)
        {
            Tag t = new Tag();
            t.tagWord = tagWordIn;

            context.Tags.AddObject(t);
            context.Films.SingleOrDefault(x => x.filmId == filmIdIn).Tags.Add(t);
        }
        else
        {
            Tag t = context.Tags.SingleOrDefault(x => x.tagWord == tagWordIn);
            context.Films.SingleOrDefault(x => x.filmId == filmIdIn).Tags.Add(t);
        }
    }

Any help with this will be greatly appreciated.

Upvotes: 1

Views: 1569

Answers (2)

Coding Flow
Coding Flow

Reputation: 21881

You need to save the changes back to the DB

e.g.

context.SaveChanges()

Also

Whilst this like will work

if (context.Tags.SingleOrDefault(x => x.tagWord == tagWordIn) == null)

It is more semantically correct to do

if (!context.Tags.Any(x => x.tagWord == tagWordIn))

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245419

You're not calling context.SaveChanges() at any point.

Without that call, nothing would be written to the database at all.

Upvotes: 4

Related Questions