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

ucMedia
  • 4,105
  • 4
  • 38
  • 46
mko
  • 6,638
  • 12
  • 67
  • 118
  • So what do you expect the value of column Hash to be inserted when you add an empty object? – Omar.Alani Nov 16 '14 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 https://entityframework.codeplex.com/discussions/471061 – mko Nov 16 '14 at 12:35
  • http://stackoverflow.com/questions/584556/how-to-use-default-column-value-from-database-in-entity-framework – mko Nov 16 '14 at 12:39

1 Answers1

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.

Omar.Alani
  • 4,050
  • 2
  • 20
  • 31
  • 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 – mko Nov 16 '14 at 14:29
  • I have updated the answer to give some more details. – Omar.Alani Nov 16 '14 at 22:26
  • You did provide some info, so I will mark it as an answer – mko Nov 16 '14 at 23:39