Sir,
Since, you are using one to one relationship, then there is no need to have ICollection of the other entity.
The exceptions occur because the connections are present in a connection pool, so when we use the context to connect to database table a connection is pulled and used. So the connection needs to be disposed after being used, here disposed actually means, itreturns back to the pool.
using(var testContext = new ContextName)
{
}
With the use of using(), the dbContext object gets disposed after use.
For the query you have stated,
the query can be written as:-
var userProfiles = context.UserInfo.Include( s => s.UserProfiles).Where(Condition goes here);
The structure should be like:-
[Table("UserInfo")]
public class UserInfo
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Key, ForeignKey("UserProfile")]
public int UserId { get; set; }
public UserProfile UserProfiles { get; set; }
I hope the DBContext would be like as below:-
public class UserContext : DbContext
{
public DbSet<UserInfo> UserInfos { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
}
Sir,
It is advisable to avoid using many context for many queries. We can avoid that using Dependency Injection or the using()statement and inside that one context instantiated is used. So, the same context should be used disposing after the use.
Override Method Dispose is also used, by inheriting the repository from IDisposible
public void Dispose()
{
db.Dispose();
}
Hope I managed to convey atleast something Sir.
Thanks.
:)