【问题标题】:Problem mapping one to many relationship with EF CTP4与 EF CTP4 映射一对多关系的问题
【发布时间】:2010-11-15 18:19:07
【问题描述】:

我正在尝试定义类别和项目之间的一对多关系(一个类别可以有一个或多个项目,一个项目可以有一个或没有类别)

public class Project : Entity {

    public virtual string Title { get; set; }

    public virtual Guid? CategoryId { get; set; }
    public virtual Category Category { get; set; }
}

public class Category : Entity {       
    public virtual string Name { get; set; }
    public virtual ICollection<Project> Projects { get; set; }
}

我已经定义了以下映射:

            modelBuilder.Entity<Project>()
            .MapSingleType(p => new {
                ProjectId = p.Id,
                p.CategoryId,
                p.Title,
                p.Slug,
                p.ShortDescription,
                p.Description,
                p.CreatedOn,
                p.UpdatedOn
            })
            .ToTable("Projects");

        modelBuilder.Entity<Category>()
            .MapSingleType(c => new {
                CategoryId = c.Id,
                c.Name,
                c.CreatedOn,
                c.UpdatedOn
            })
            .ToTable("Categories");

        // relationships
        modelBuilder.Entity<Project>()
            .HasOptional<Category>(p => p.Category)
            .WithMany()
            .HasConstraint((p, c) => p.CategoryId == c.Id);

现在虽然这似乎工作正常,但 EF 仍在生成 Categories_Products 表(用于多对多关联)。

我已禁用默认数据库初始化程序,但仍在生成此表。我做错了什么?

谢谢 本

【问题讨论】:

    标签: entity-framework-4 ef-code-first


    【解决方案1】:

    我删除了项目和类别映射代码,让 EF 使用默认约定来创建数据库。这创造了我所期望的关系(类别和项目之间的一对多)。

    我要补充一点,我明确定义映射的唯一原因是因为 EF 似乎不能很好地处理基类。我有一个基类“Entity”,它有一个属性“Id”,我的所有实体都继承自该属性。这对 CTP4 造成了很多问题,我只是将它与接口 IEntity 交换。这仍然给了我在使用通用存储库类时所需的约束。

    希望 RTM 能更好地支持实体基类

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多