这应该是一个简单的问题, 我不明白为什么会这样:
错误:
尝试通过电动工具生成这些模型时,我收到此错误, 当我试图在另一个项目中添加关于这些的迁移时,我也遇到了类似的错误。
Activity_ActivityResult_Target: : Multiplicity is not valid in Role 'Activity_ActivityResult_Target' in relationship 'Activity_ActivityResult'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
我们在relationship
策略中使用了2个简单的类code-fisrt
。
Desired: Activity 1 ----> ActivityResult 0-1
整个代码:
public class Activity
{
[Key]
public int Id { get; set; }
public DateTime? ActivityDate{ get; set;}
// Tested with and without these commented part, I didn't think it should be
//[ForeignKey("ActivityResult")]
//public int? ActivityResultId { get; set; }
public virtual ActivityResult ActivityResult { get; set; }
}
//---------------
public class ActivityResult //: Entity
{
[Key]
public int Id { get; set; }
public int Score1 { get; set; }
public int Score2 { get; set; }
[ForeignKey("Activity")]
[Required]
public int ActivityId { get; set; }
public virtual Activity Activity { get; set; }
}
// ---------------
public class Context : DbContext
{
public DbSet<Activity> Activities { get; set; }
public DbSet<ActivityResult> ActivityResults { get; set; }
}
为什么呢?解决方案是什么?
答案 0 :(得分:2)
在一对一的关系中,外键也是主键。
您需要更改ActivityResult
以删除Id
属性,并且只有ActivityId
。它将包含[Key]
和[ForeignKey]
:
public class ActivityResult //: Entity
{
[Key]
[ForeignKey("Activity")]
[Required]
public int ActivityId { get; set; }
public int Score1 { get; set; }
public int Score2 { get; set; }
public virtual Activity Activity { get; set; }
}
以下是Entity Framework如何使用迁移创建表。您会注意到ActivityResults未将ActivityId定义为Identity。这是因为它无法自动生成。为了成为一对一,它必须在“活动”中具有匹配的行。它是主键,因此它是独一无二的。如果你同时拥有ActivityId和Id而Id是主键,那么你真的有一对多的关系。
CreateTable(
"dbo.Activities",
c => new
{
Id = c.Int(nullable: false, identity: true),
ActivityDate = c.DateTime(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ActivityResults",
c => new
{
ActivityId = c.Int(nullable: false),
Score1 = c.Int(nullable: false),
Score2 = c.Int(nullable: false),
})
.PrimaryKey(t => t.ActivityId)
.ForeignKey("dbo.Activities", t => t.ActivityId)
.Index(t => t.ActivityId);
答案 1 :(得分:1)
@Dismissile是对的,但是正确的代码是:
public class Activity {
[Key]
public int Id { get; set; }
public DateTime? ActivityDate { get; set; }
public virtual ActivityResult ActivityResult { get; set; }
}
//---------------
public class ActivityResult {
[Key]
public int Id { get; set; }
public int Score1 { get; set; }
public int Score2 { get; set; }
//public int ActivityId { get; set; }
[ForeignKey("Id")]
[Required]
public virtual Activity Activity { get; set; }
}
给出以下表格:
CREATE TABLE [dbo].[Activities](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ActivityDate] [datetime] NULL,
CONSTRAINT [PK_dbo.Activities] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
和
CREATE TABLE [dbo].[ActivityResults](
[Id] [int] NOT NULL,
[Score1] [int] NOT NULL,
[Score2] [int] NOT NULL,
CONSTRAINT [PK_dbo.ActivityResults] PRIMARY KEY CLUSTERED
(
[Id] ASC
)