实体框架的从属增量主键

时间:2018-07-05 19:27:40

标签: c# sql sql-server entity-framework entity-framework-6

我第一次使用C#,Entity Framework 6.1.3代码优先,SQL Server,并且在创建依赖的自动增量键时遇到问题。

我有这个:

version: '2.1'
volumes:
  project:
services:
  waitfordb:
      image: dadarek/wait-for-dependencies
      depends_on:
        - postgres
      command: postgres:5432
  postgres:
    restart: always
    image: postgres:10.4
    environment:
      - POSTGRES_USER=
      - POSTGRES_PASSWORD=
      - POSTGRES_DB=
    volumes:
      - ./postgres-data/postgres:/var/lib/postgresql/data
    ports:
      - "5432:5432" #for connection inside the docker container
  nginx:
   restart: always
   build: ./nginx
   ports:
     - "80:80"
     - "8080:8080"
   volumes:
     - project:/app
   depends_on:
     - api
  api:
    restart: always
    build:
      context : .
      dockerfile: app/Dockerfile
    ports:
      - 8000:8000
    volumes:
      - project:/app
    depends_on:
      - postgres

我对类class One { [Key] [Required] string exampleKey { get; set; } string otherProperty { get; set; } } class Two { [Required] [Key] [Column(Order = 0 )] public string exampleKey { get; set; } [ForeignKey("exampleKey")] public virtual One one { get; set; } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column(Order = 1)] [Required] public long Version { get; set; } public string otherProperty { get; set; } } 的{​​{1}}属性感兴趣,当您插入数据时,它的ID就像

Version

Two

One

|exampleKey|otherProperty|
|"test"    |"random data"|
|"test2"   |"more random"|

但是我正在寻找类似的东西

Two

很久以前,我正在寻找解决此问题的方法,这可能吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

不容易,不。但是,您可以通过日期戳或标识列来得出最新的。然后,每当您检索数据时,只需获取具有最新日期/标识值的行即可。

您还可以编写一个视图,以显示我刚才提到的行为。

类似这样的东西:

假数据

* @return the absolute paths to application-specific directories. Some
* individual paths may be {@code null} if that shared storage is
* not currently available.

查看方法

if object_id('dbo.Data') is not null drop table dbo.Data
create table dbo.Data
(
    RID int identity(1,1) primary key clustered,
    ExampleKey varchar(10),
    OtherProperty varchar(100)
)

-- initial insert
insert into dbo.Data (ExampleKey, OtherProperty)
values ('test', 'Random data'), ('test2', 'more random')

-- Second insert
insert into dbo.Data (ExampleKey, OtherProperty)
values ('test', 'Random data'), ('test2', 'more random')

替代

如果您需要在插入表时将其保留在表中,则可能需要一个触发器(我不建议这样做)。