Hi I have a database to be setup as follows:
It has a User
who belongs to an Area
:
public class User : IEntity
{
public int UserId { get; set; }
public string Username { get; set; }
public int AreaId { get; set; }
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; se开发者_开发知识库t; }
//Navigation properties
public virtual Area Area { get; set; }
}
It has an Area
which has a DefaultAdmin
of type User
:
public class Area : IEntity
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int DefaultAdminId { get; set; }
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
}
// Navigation properties
public virtual User DefaultAdmin { get; set; }
}
Is it even possible to set something up like this? They both require each other so when starting with these tables empty you can never create one because the former requires the later.
Assuming the underlying table schemas have NOT NULL constraints on the foreign keys, this set of relationships would also be problematic from the database side of things (even if leaving EntityFramework out of the picture)
You will be able to do one of the following:
a) Reconsider the relationships between areas and users
b) Or if the relationship described really is accurate:
- temporarily relax the requirement such that a first user can be created without an area
- create a first user (perhaps AdminUser)
- create a first area with the first user as the DefaultAdmin
- associate the first user with the area created in the previous step
- reinstate the relationship requirements as described in the question
The steps above could be done as part of a database initialization script run when deploying a database. Once a first area and user exist, you will be able to add more without breaking the requirements described.
I should point out that the relationships are not really one-to-one as described in the title of the question as:
- A user could be the DefaultAdmin for many areas (1 to many)
- An area can have many users (1 to many)
Hope that helps...
精彩评论