开发者

Non-null many-to-zero-or-one relationship in EF code first?

I have a classic one-to-many relationship except there's no "one" for every item on the "many" side. Here are my tables:

SESSIONS:

ID        IP
1         1.1.1.1
2         2.2.2.2

USERS:

IP        NAME
1.1.1.1   John

...generated from the following POCO's:

public class Session {
    public int     id   { get; set; }
    public long    ip   { get; set; }
}

public class User {
    [Key]
    public long    ip   { get; set; }
    public string  name { get; set; }
    public ICollection<Session> sessions { get; set; }
}

Some sessions have a corresponding user (by IP). I'd like to retain the IP even if there is no associated user, and to be able to navigate User.sessions.

With the POCO's above, EF will understandably generate a FK from Session.ip to 开发者_开发技巧User.ip, preventing me from inserting Sessions with an IP that is not correlated to a user. Making Session.ip nullable allows me to insert sessions not related to a user, but then I lose the IP (it must be null).

Is there any way to achieve this?

A million thanks.


I would modify the POCO classes like this:

 public class Session
{
    public int id { get; set; }
    public long ip { get; set; }      
    public User User {get;set;}
}

public class User
{
    [Key]
    public int id { get; set; }
    public long ip { get; set; }
    public string name { get; set; }
    public ICollection<Session> sessions { get; set; }
}

this will Create a Nullable User_id field on the Session Table and should give you the desired results. Please note that this has removed ip as the PK on the User table and changed it to a generic integer id.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜