3

To keep working in an application with data from database, I'm using linq2db.

The insertion of an object in DB was expected to insert WITH ID if that object has one, and to create new ID in DB for this object if there is no identity.
But for now, this method is inserting new id in both cases.

I can give you an example:

using(var db = new EIDB())
{
  Customer.Id=20;
  Customer.Name="Greg";
  db.Insert(Customer);
}

After this insertion, we have in DB this customer with name "Greg" and ID=1...

***Is there a way to do something similar, but to insert the same ID that was set before(in our example = 20)?

PS: If I'm using NpgsqlCommand, and inserting the same data, is inserting with ID=20...

BAndrei
  • 199
  • 2
  • 11

3 Answers3

4

I found a solution. If i'm using just db.Insert(Customer) is creating a new instance in database with new ID. But, if I'm doing like this:

db.Customers
  .Value(p => p.Name, Customer.Name)
  .Value(p => p.Id, Customer.Id)
  .Insert();

This is inserting in database the instance with the id set before.

Good luck for those who had the same problem :)

BAndrei
  • 199
  • 2
  • 11
4

I suspect you have Id column marked as identity by IdentityAttribute attribute or ColumnAttribute.IsIdentity = true

It tells linq2db to use auto-generated value when inserting record using insert methods without explicit field setters like Insert(object) method or MergeAPI's InsertWhenNotMatched([predicate]) operation.

This logic is not applied to operations with explicit field setters like Insert(() => new Record(){Id = explicitValue}), .Value(() => Id, value).Insert() or InsertWhenNotMatched(target => new Record(){Id = explicitValue}[, predicate]). In those cases because you explicitly tell linq2db which value to insert into identity field - it will use value you provided.

-2

Please try use this code:

using (dbFoodBlogEntities db = new dbFoodBlogEntities())
{
    db.tblBloggers.AddObject(objtblBlogger);
    db.SaveChanges();
}
Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
Akash Kool
  • 52
  • 5