0

假设您有以下模型:

public class Dog {
  public int DogId { get; set; }
  public string Name { get; set; }
}

public class Cat {
  public int CatId { get; set; }
  public string Name { get; set; }
}

// This model/table allows us to link multiple colors to an animal
// Lets say type of 1 is dog, 2 is cat for simplicity
public class AnimalColor {
  public int ObjectId { get; set; }
  public int TypeId { get; set; }
  public virtual Color Color { get; set; }
}

public class Color {
  public int ColorId { get; set; }
  public string Description { get; set; }
}

这种架构的问题在于,AnimalColor 在技术上是 Dog 和 Cat 的导航属性,但它的复杂性使您无法使用“内置”功能,例如 AnimalColor 和 Color 之间的关系。

Dog 和 AnimalColor 之间的关系具有 TypeId 的条件,更不用说 ForeignKey 将无法正常工作,因为键名不一样(DogId 和 ObjectId)。

我的问题是:我是否完全错过了使这项工作有效的东西?如果不是,如果我想拉出以 AnimalColors 作为属性的 Dogs 列表,那么处理这种情况的最佳方法是什么?

目前,我对此唯一的解决方案是在遍历 Dogs 时拉出两个列表并获取颜色。似乎应该有一个更优雅的方式。

4

1 回答 1

0

根据我从您的问题中了解到的情况,我会这样写”

public class Animal {
  public int ID { get; set; }
  public List<Color> Colors { get; set; }
  public string Name { get; set; }
}
public class Dog : Animal { }

public class Cat : Animal { }

这种方式你不需要TypeId,你可以像这样验证类型:

Cat a = new Cat();
Dog b = new Dog();
Animal c = new Dog();
if (a is Cat) {...}  // true
if (b is Dog) {...}  // true
if (c is Dog) {...}  // true

如果你有更多的颜色:

a.Colors.Add(new Color(255, 255, 255));
a.Colors.Add(new Color(100, 100, 0));

但我不能 100% 确定这是否是您的问题。

于 2011-10-26T13:02:56.553 回答