David
David

Reputation: 965

LINQ - Generate identity for object

Context:

A User is an Entity and a Group consists of 1 or more Entities. A user logs in with his email not his entityID (= userID). When a user needs to be created he fills in a form with the information in the USER table (excl. his userID ofc). To generate the user's ID, I first need to generate his ID in the ABSTRACT_ENTITY table because the groupID's and the userID's have to be unique (read: must never collide)

Question:

In other cases it's rather easy because you just fill in the other rows and it generates it automatically, but in this case there are no other rows...

Database Diagram

Upvotes: 1

Views: 847

Answers (3)

Jens Kloster
Jens Kloster

Reputation: 11277

Put the things that User and Group have in common in the table abstract_entity

If you can't think of something, then just add a "Created" field (as a datatime). This will be enought to let EF generate a value for abstract_entity.Id.
With EF, identity fields that are automatic set, should be ignored when you create the record.
Which is why it cannot be the only field on a table

Upvotes: 1

David
David

Reputation: 965

SOLUTION

Abstract_Entity ae = new Abstract_Entity();
Entities.Abstract_Entity.Add(ae);
Entities.SaveChanges();

User u = new User();
u.email = email;
u.userID = ae.ID;
Entities.User.Add(u);
Entities.SaveChanges(); 

Upvotes: 1

Imapler
Imapler

Reputation: 1422

Some sudocode

Abstract_Entity entity = new Abstract_Entity();
entity.ID = Guid.NewGuid();

User user = new User();
//fill with user data
user.userID = entity.ID;

MyContext db = new MyContext();
db.Abstract_Entitys.Attach(entity);
db.Users.Attach(user);
db.SubmitChanges();

The idea here is that all the ID's are of the sql type uniqueidentifier which is the c# type Guid. Guids are for all intents and purposes unique http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates

if you dont want to generate the guids in the code you can configure your database context to auto generate values by setting AutoGenerateValues to true and in the database set the DefaultValueOrBinding to (newid())

Upvotes: 2

Related Questions