How to declare one to one relationship using Entity Framework 4 Code First (POCO)

后端 未结 4 1762
轻奢々
轻奢々 2020-11-27 17:00

How to declare a one to one relationship using Entity Framework 4 Code First (POCO)?

I found this question (one-to-one relationships in Entity Framework 4) , but the

4条回答
  •  庸人自扰
    2020-11-27 17:30

    Are you just looking for something like this?

    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public Profile Profile { get; set; }
        public int ProfileId { get; set; }
    }
    
    public class Profile
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PostalCode { get; set; }
        // etc...
    }
    
    public class UserMapping : EntityConfiguration
    {
        public UserMapping()
        {
            this.HasKey(u => u.Id);
            this.Property(u => u.Username).HasMaxLength(32);
    
            // User has ONE profile.
            this.HasRequired(u => u.Profile);
        }
    }
    
    public class ProfileMapping : EntityConfiguration
    {
        public ProfileMapping()
        {
            this.HasKey(p => p.Id);
            this.Property(p => p.FirstName).HasMaxLength(32);
            this.Property(p => p.LastName).HasMaxLength(32);
            this.Property(p => p.PostalCode).HasMaxLength(6);
        }
    }
    

    EDIT: Yeah I didn't have VS in front of me but you need to add the following line in the UserMapping instead of the current HasRequired and also add a ProfileId property (instead of Profile_Id that you added):

    this.HasRequired(u => u.Profile).HasConstraint((u, p) => u.ProfileId == p.Id);
    

    I currently don't think there's a way around this, but I'm sure it'll change since we're only in CTP4. It'd be nice if I could say:

    this.HasRequired(u => u.Profile).WithSingle().Map(
        new StoreForeignKeyName("ProfileId"));
    

    This way I wouldn't have to include a ProfileId property. Maybe there is a way around this currently and it's still to early in the morning for me to think :).

    Also remember to call .Include("Profile") if you want to include a "navigational property".

提交回复
热议问题