首先是表Entity Framework代码中的2个主键

时间:2018-04-20 09:02:29

标签: c# sql-server entity-framework ef-code-first

我在SQL Server中有3个表。我想首先在实体框架上使用代码,我想要相互导航这些表。如您所见KioskBatch同时具有复合键和两个复合键之一作为外键,但是当尝试插入时,我收到此错误:

  

该物业' KioskId'无法配置为导航属性。该属性必须是有效的实体类型,并且该属性应具有非抽象的getter和setter。对于集合属性,类型必须实现ICollection,其中T是有效的实体类型。

代码:

[Table("tblKiosk")]
public class Kiosk
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("Id")]
    public int KioskId { get; set; }
}

[Table("tblCompletionStatus")]
public class CompletionStatus
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Status { get; set; }
}

[Table("tblKioskBatch")]
public class KioskBatch
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int KioskBatchId { get; set; }

    public int KioskId { get; set; }

    [Key,ForeignKey("KioskId")]
    public virtual Kiosk Kiosk { get; set; }

    [ForeignKey("CompletionStatus"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int? CompletionStatusId { get; set; }
    public virtual CompletionStatus CompletionStatus { get; set; }
}


CREATE TABLE [dbo].[tblKiosk]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK_tblKiosk] 
        PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[tblKioskBatch]
(
    [KioskBatchId] [int] NOT NULL,
    [KioskId] [int] NOT NULL,
    [CompletionStatusId] [int] NULL,

    CONSTRAINT [PK_tblKioskBatch] 
        PRIMARY KEY CLUSTERED ([KioskBatchId] ASC, [KioskId] ASC)
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblKioskBatch] WITH CHECK 
    ADD CONSTRAINT [FK_tblKioskBatch_tblCompletionStatus] 
    FOREIGN KEY([CompletionStatusId]) REFERENCES [dbo].[tblCompletionStatus] ([Id])
GO

ALTER TABLE [dbo].[tblKioskBatch] CHECK CONSTRAINT [FK_tblKioskBatch_tblCompletionStatus]
GO

ALTER TABLE [dbo].[tblKioskBatch]  WITH CHECK 
    ADD CONSTRAINT [FK_tblKioskBatch_tblKiosk] 
    FOREIGN KEY([KioskId]) REFERENCES [dbo].[tblKiosk] ([Id])
GO

ALTER TABLE [dbo].[tblKioskBatch] CHECK CONSTRAINT [FK_tblKioskBatch_tblKiosk]
GO

CREATE TABLE [dbo].[tblCompletionStatus]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Status] [nvarchar](50) NULL,

    CONSTRAINT [PK_TblCompletionStatus] 
        PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

2 个答案:

答案 0 :(得分:2)

您可以在映射时设置由2构成的主键,例如

    modelBuilder.Entity<YouEntity>()
       .HasKey(e => new { e.Key1, e.Key2} )

答案 1 :(得分:0)

有关Fluent API(HasKey)的更多信息

代码示例(如果链接不可访问)。

public class SampleContext : DbContext
{
    public DbSet<Order> Orders { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>()
            .HasKey(o => o.OrderNumber);
    }
}
public class Order
{
    public int OrderNumber { get; set; }
    public DateTime DateCreated { get; set; }
    public Customer Customer { get; set; }
    ...
)