Reputation: 61041
How can I ensure that EF generates the same Id for the same occurence of an object?
E.g. if I have a class like:
class Foo{
ICollection<Bar> Bar1;
ICollection<Bar> Bar2;
}
If I create a new entity Foo
and add a single instance of Bar
(no id set) to both Bar1
and Bar2
- will it use the same Id for both or create a new one each time? E.g.:
var bar = new Bar();
var foo = new Foo{
Bar1 = new List<Bar>(){ bar };
Bar2 = new List<Bar>(){ bar };
}
context.SaveChanges();
Will Bar1
and Bar2
contain the same record bar
with the same id?
UPDATE: What if I have two instances that are the same with respect to Equals
and hash code?
var first = new Bar();
var second = new Bar(); /// first.equals(second )
var foo = new Foo{
Bar1 = new List<Bar>(){ first };
Bar2 = new List<Bar>(){ second };
}
or does EF not check for equals?
Upvotes: 2
Views: 87
Reputation: 51634
Yes, Entity Framework will create one record for foo
and one record for bar
in the database. Since both lists contain the same instance of Bar
the respective database entries will point to the same record.
Upvotes: 1