0

I'm pretty new to Entity Framework 6 and so it may be a bit difficult on how to ask this question, but essentially I have an entity configuration that is set up like so:

public class EntityExampleConfiguration : EntityTypeConfiguration<Entity>
{
    public EntityExampleConfiguration()
    {
        Map(f =>
            {
                f.Properties(p => new
                {
                    p.ID,
                    p.Status
                    p.Filed
                    p.By,
                    p.Title,
                    p.Waiver,
                    p.Notes,
                    p.Type
                });
                f.ToTable("EntityTable");
            })
        .Map(f =>
            {
                f.Properties(p => new
                {
                    p.EntityID,
                    p.EntityName,
                    p.County,
                    p.Hash
                });
                f.ToTable("View");
            });

        HasKey(f => f.ID);

        Property(f => f.ID).HasColumnName("ExID");
        Property(f => f.EntityID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        Property(f => f.EntityName).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        Property(f => f.County).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        Property(f => f.Hash).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

    }
}

Where the EntityExampleConfiguration combines a table (EntityTable) with a view (View). My problem (I believe) is that because of the way this is set up, when I try to insert something it doesn't insert:

Db.Entry(EntityObjectToInsert).State = EntityState.Added;
Db.Entity.Attach(EntityObjectToInsert);
Db.SaveChanges();

I don't get an exception or anything, and my program just continues execution, but if I stop at a breakpoint after attempting to save, EntityObjectToInsert.ID is still -1 (which is default when the object is created), and it's not in my table.

I suspect the view has something to do with this but can't find any good information on how it could be, if it even is. I am able to load data into a model and update, but inserting is a new function I am building into the application and it's the only thing not working.

jjj
  • 4,822
  • 1
  • 16
  • 39
DeveryDay
  • 161
  • 15

1 Answers1

0

If you have an entity that you know already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet. The entity will be in the Unchanged state in the context.

-- https://msdn.microsoft.com/en-us/data/jj592676.aspx


If should be fine to just set the State to Added, or even better, to use DbSet<YourEntity>.Add(). You shouldn't both set State and perform Attach().

jjj
  • 4,822
  • 1
  • 16
  • 39