1

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(){}?

3
  • So what do you expect the value of column Hash to be inserted when you add an empty object? Commented Nov 16, 2014 at 12:04
  • @Omar.Alani since db handles hash by entering newid(), I need to set hash as nullable in order to insert it from EF and let db handle identity column and newid() for hash. More about it on entityframework.codeplex.com/discussions/471061 Commented Nov 16, 2014 at 12:35
  • stackoverflow.com/questions/584556/… Commented Nov 16, 2014 at 12:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Both solutions are acceptable. But regarding solution 1. if I dont map hash column, I want be able to retrieve value via ef for it. I think that solution 2 and option to use guid instead of newid is much better
I have updated the answer to give some more details.
You did provide some info, so I will mark it as an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.