0

我必须重用现有的数据库,并且必须使用 Microsoft 的东西。我们想在我们现有的数据库之上创建一个 asp.net MVC 应用程序。DB设计如下(这是对问题的简化)

Table: Students
  id
  ....

Table: Professors
  id
  ....

Table: Images
  id
  imageble_id
  imagable_type

学生和教授可以有多个图像,一个图像属于教授或学生。在旧应用程序中,您有一个 person 类,它是学生和教授的父母。

我的问题是将多态关系 Image 映射到学生和教授。我不得不说我是 asp.net mvc 和实体框架的新手。但我似乎没有找到一种方法来让它发挥作用。这样当你这样做时:

Professor a = MyAppDbContext.Professors.find(1)
a.Images.add(new Image())

它在数据库中创建一个新图像,其中

imageble_id = 1
imagable_type = "Professor"

我尝试按照数据库优先方法的建议定义自己的映射,但我找不到如何映射这个多态外键。

ps:我知道数据库因此不是第三范式,但是不允许更改数据库。

4

1 回答 1

0

我不明白你的问题......事实上,我在这里没有看到任何问题......

向您的类添加构造函数Image

public Image(int id, string type)
{
    this.Id = id;
    this.Type = type;
}

然后,您的代码可以类似于以下内容:

Professor a = MyAppDbContext.Professors.find(1);
a.Images.add(new Image(1, "Professor"));
MyAppDbContext.SaveChanges();

如果您正在创建教授:

Professor a = new Professor(...);
MyAppDbContext.Professors.Add(a);
MyAppDbContext.SaveChanges();

a.Images.add(new Image(a.Id, "Professor"));
myDbContext.SaveChanges();

更新:通过对 db 的单个查询获取所有教授的图像。

如果您正确声明了导航属性,您只需要以下行来创建一个内存中的教授列表,其中包含他们的图像在一个数据库查询中:

var ps = MyAppDbContext.Professors.ToList();

现在,例如,要获取教授的图像,您可以使用以下命令,它不会导致对 db 的查询(因为该集合存在于内存中):

var picsOfProf = ps.FirstOrDefault(p => p.Id == 1).Images.ToList();
于 2013-09-18T05:49:34.180 回答