How to define relationships programmatically in Entity Framework 4.1's Code-First Fluent API

后端 未结 2 1937
挽巷
挽巷 2021-02-01 23:43

I\'m playing around with the new EF4.1 unicorn love.

I\'m trying to understand the different ways I can use code-first to programatically

2条回答
  •  佛祖请我去吃肉
    2021-02-02 00:05

    Here you have examples you are looking for:

    public class User
    {
        public int Id { get; set; }
        ...
        public Foo Foo { get; set; }
        public Team Team { get; set; }
        public UserStuff UserStuff { get; set; }
    }
    
    public class Team
    {
        public int Id { get; set; }
        ...
        public ICollection Users { get; set; }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        ...
    }
    
    public class UserStuff
    {
        public int Id { get; set; }
        ...
    }
    
    public class Context : DbContext
    {
        public DbSet Users { get; set; }
        public DbSet Foos { get; set; }
        public DbSet Teams { get; set; }
        public DbSet UserStuff { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                .HasRequired(u => u.Team)
                .WithMany(t => t.Users);
    
            modelBuilder.Entity()
                .HasOptional(u => u.Foo)
                .WithRequired();
    
            modelBuilder.Entity()
                .HasRequired(u => u.UserStuff)
                .WithRequiredPrincipal();
        }
    }
    

提交回复
热议问题