DbSet.Add() not working

user3861672 picture user3861672 · Jul 21, 2014 · Viewed 7.6k times · Source

I have a class like this:

[Table("member_activation")]
public partial class MemberActivation
{
    [Key]
    public Int64 member_id { get; set; }
    public String token { get; set; }
}

My db:

public class SMADbContext : DbContext
{
    public SMADbContext() : base("SMADB")
    {
        Database.SetInitializer<SMADbContext>(new NullDatabaseInitializer<SMADbContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Member> Members { get; set; }
    public DbSet<MemberActivation> MemberActivations { get; set; }
    public DbSet<ApiAccount> ApiAccounts { get; set; }
    public DbSet<ApiHardware> ApiHardwares { get; set; }
    public DbSet<MemberRelation> MemberRelations { get; set; }
}

In my controller:

    [Route("tester")]
    [AllowAnonymous]
    public IHttpActionResult tester()
    {
        using (var db = new SMADbContext())
        {
            var memberActivation = new MemberActivation();
            memberActivation.member_id = 10155;
            memberActivation.token = "hello";

            db.MemberActivations.Add(memberActivation);
            return Json(new { dbset = db.MemberActivations.ToList(), memberAct = memberActivation });

        }
    }

db.MemberActivations.Add(memberActivation); does not work. When I return the json, the dbset does not include the newly created memberActivation. I do not have db.SaveChanges() because it will not save until the memberActivation is pushed to the dbset

Answer

Richard France picture Richard France · Jul 21, 2014

You cant set member_id, it is the key and ef uses it as identity. It will be ignored. You can configure ef so that member_id is not identity but that's another topic.

 db.MembershipActivations.Add( new MemberActivation { token = "hello"}):
 db.SaveChanges();

should work fine.

if however , as it would appear , you have an existing member and you are trying to set a relationship with that entity via a join table. Then you should retrieve that entity and set the memberactivation. Ef will sort the rest out for you. Bit of guessing here as i would need to see the involved entities.