mko
mko

Reputation: 7325

Add a record via Entity Framework containing no values

How can add a record via Entity Framework to a table that contains one identity column and one Hash column that automatically assign value via newid().

Here is my code.

using (GM.Entity.Entities context = new GM.Entity.Entities())
            {
                var q = context.xattachment.Add(new Entity.xattachment(){});
                context.SaveChanges();

                return q.AttachmentID;
            }

When I add a value like new Entity.xattachment(){ Hash = "1234"} it works fine. How to add a row with not values such as new Entity.xattachment(){}?

Upvotes: 1

Views: 45

Answers (1)

Omar.Alani
Omar.Alani

Reputation: 4130

Entity framework will generate a sql from these values, so to achive what you need, do one of those two options

  1. Don't map the hash property and let the sql database inserts the default which is a newid(), but this means EF will never know about that column and you cannot retrieve it as you do normally when you load your entity.

  2. Add a constructor to your entity and initialize the hash property to new value and so you don't need to initialize it when you add your entity, I personally prefer this option as it gives you the flexibility to override the value if you code decided to pass the hash value and you still can retrieve it when you load your entity.

Hope that help.

Upvotes: 2

Related Questions