MVC3 模型和复杂的关系
假设您有以下模型:
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 之间的关系和颜色。
Dog 和 AnimalColor 之间的关系有一个 TypeId 条件,更不用说外键将无法正常工作,因为键名称不同(DogId 和 ObjectId)。
我的问题是:我是否完全错过了使这项工作有效的东西?如果不是,如果我想提取以 AnimalColors 作为属性的狗列表,处理这种情况的最佳方法是什么?
目前,我对此唯一的解决方案是拉两个列表并在循环遍历狗时抓取颜色。看来应该有更优雅的方式。
Lets say you have the following models:
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; }
}
The problem with this architecture is that AnimalColor is technically a navigation property of both Dog and Cat, but the complexity of it stops you from being able to use the "built in" features like the relationship between AnimalColor and Color.
The relationship between Dog and AnimalColor has a condition of TypeId, not to mention the ForeignKey won't properly work because the key names aren't the same (DogId and ObjectId).
My question is this: am I totally missing something that makes this work? If not, what's the best way to handle this type of situation if I want to pull a list of Dogs with the AnimalColors as a property?
Currently the only solution I have for this is to pull two lists and grab the colors as I loop through the Dogs. Seems like there should be a more elegant way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我对你问题的理解,我会这样写“
这样你就不需要
TypeId
,你可以像这样验证类型:如果你有更多的多种颜色:
但我不是100% 确定这是否是您的问题。
From what I understand from your question, I would write like this"
This way you don't need
TypeId
, you can verify the type like this:if you have more mulyiple colors:
But I'm not 100% sure if that was your problem.