1
我想简单地选择数据库中的版本和模板组合。MVC 3使用实体框架的多表到多表的模型
这里是分贝结构:
CREATE Table ProductVersion(
id int not null primary key Identity,
Product_ID int not null,
Version decimal(18,1) not null,
Active bit not null,
LicenseVersion int not null,
FOREIGN KEY (Product_ID) References Products(id)
)
Create Table CodeTemplates(
id int not null primary key Identity,
Name varchar(50) not null,
DLT_ID int not null,
QuantityRule_ID int,
SerialRule_ID int,
DurationRule_ID int,
foreign key (DLT_ID) References DisplayedLicenseTypes(id),
foreign key (QuantityRule_ID) References Rulesets(id),
foreign key (SerialRule_ID) References Rulesets(id),
foreign key (DurationRule_ID) References Rulesets(id)
)
CREATE table ProductVersion_CodeTemplate(
ProductVersion_ID int not null,
CodeTemplate_ID int not null,
CONSTRAINT PK_Restrictions Primary Key Clustered
(
ProductVersion_ID asc,
CodeTemplate_ID asc
),
foreign key (ProductVersion_ID) References ProductVersion(id),
foreign key (CodeTemplate_ID) References CodeTemplates(id)
)
下面是使用了指productversion和CodeTemplates当前机型:
[Table("ProductVersion")]
public class ProductVersionModel
{
public int ID { get; set; }
public virtual ProductModel Product { get; set; }
[DisplayFormat(DataFormatString = "{0:F1}",ApplyFormatInEditMode=true)]
public decimal Version { get; set; }
public bool Active { get; set; }
public int LicenseVersion { get; set; }
}
[Table("CodeTemplates")]
public class TemplateModel
{
public int ID { get; set; }
public string Name { get; set; }
public virtual DisplayedLicenseTypeModel DLT { get; set; }
public virtual List<LicenseFlagModel> LicenseFlags { get; set; }
public virtual RulesetModel QuantityRule { get; set; }
public virtual RulesetModel SerialRule { get; set; }
public virtual RulesetModel DurationRule { get; set; }
}
以下是我尝试使用:
[Table("ProductVersion_CodeTemplate")]
public class ProductVersionWithTemplateModel
{
[Key, Column(Order = 0)]
public virtual ProductVersionModel ProductVersion { get; set; }
[Key, Column(Order = 1)]
public virtual TemplateModel CodeTemplate { get; set; }
}
弹出的第一个错误是:
0123模型生成过程中检测到个一个或多个验证错误:
System.Data.Edm.EdmEntityType:的EntityType 'ProductVersionWithTemplateModel' 不具有确定的键。为此EntityType定义密钥 。 System.Data.Edm.EdmEntitySet:EntityType: EntitySet“应用模板”基于类型 “ProductVersionWithTemplateModel”,它没有定义键。
我在这里丢失了什么,dbmodelbuilder绑定?
ANSWER(因为格式是在注释可怕):
[Table("ProductVersion_CodeTemplate")]
public class ProductVersionWithTemplateModel
{
[Key, Column(Order = 0)]
public int ProductVersion_ID { get; set; }
[ForeignKey("ProductVersion_ID")]
public virtual ProductVersionModel ProductVersion { get; set; }
[Key, Column(Order = 1)]
public int CodeTemplate_ID { get; set; }
[ForeignKey("CodeTemplate_ID")]
public virtual TemplateModel CodeTemplate { get; set; }
}
我几乎尝试了同样的事情,但我没有将foreignkey属性应用于虚拟类型。任何想法或文章都会帮助我理解为什么当它们存在于虚拟属性中时,我将不得不在该模型中提供int字段?非常感谢答案! – Csharpfunbag
几乎完美的答案,除了我有一些与外部键不匹配在数据库中的实际ID字段有问题。我在原始文章中提供了一个更好的格式来寻找答案。再次感谢TravisJ的回答! – Csharpfunbag