Creating Composite Key Entity Framework

If Device table has composite primary key, then you need same composite foreign key on your NotificationMessageDevice table. How would SQL find Device without full primary key? Also you should make these fields to be part of NotificationMessageDevice table primary key. Otherwise you can’t guarantee primary key will be unique: public class NotificationMessageDevice { [Column(Order … Read more

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

Edit: Original answer used Find instead of Local.SingleOrDefault. It worked in combination with @Juan’s Save method but it could cause unnecessary queries to database and else part was probably never executed (executing the else part would cause exception because Find already queried the database and hadn’t found the entity so it could not be updated). … Read more

Entity Framework Multiple Column as Primary Key by Fluent Api

Use anonymous type object instead of 2 separated statements: HasKey(pc => new { pc.ProductId, pc.CategoryId }); From Microsoft Docs: EntityTypeConfiguration.HasKey Method If the primary key is made up of multiple properties then specify an anonymous type including the properties. For example, in C# t => new { t.Id1, t.Id2 } and in Visual Basic .Net … Read more

Entity Framework 5 deep copy/clone of an entity

One cheap easy way of cloning an entity is to do something like this: var originalEntity = Context.MySet.AsNoTracking() .FirstOrDefault(e => e.Id == 1); Context.MySet.Add(originalEntity); Context.SaveChanges(); the trick here is AsNoTracking() – when you load an entity like this, your context do not know about it and when you call SaveChanges, it will treat it like … Read more

Mocking EF DbContext with Moq

I managed to solve it by creating a FakeDbSet<T> class that implements IDbSet<T> public class FakeDbSet<T> : IDbSet<T> where T : class { ObservableCollection<T> _data; IQueryable _query; public FakeDbSet() { _data = new ObservableCollection<T>(); _query = _data.AsQueryable(); } public virtual T Find(params object[] keyValues) { throw new NotImplementedException(“Derive from FakeDbSet<T> and override Find”); } public … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)