zoukankan      html  css  js  c++  java
  • EF code first,set composite primary key 复合key问题

    环境:

    EF core 2.0

    Net core 2.0

    错误:

    因实体定义了多个key,打开数据库时程序报以下错误

    An unhandled exception occurred while processing the request.

    InvalidOperationException: Entity type '***' has composite primary key defined with data annotations. To set composite primary key, use fluent API.

    具体的意思是无效的操作异常:实体(****)使用"data annotations"的方式已经定义了复合key。设置复合key,请使用“fluent API”方式。

     

    解决方式:

    官方文档 http://msdn.microsoft.com/en-us/data/JJ591617.aspx#1.2

    There are two main ways you can configure EF to use something other than conventions, namely  annotations or EFs fluent API. The annotations only cover a subset of the fluent API functionality, so there are mapping scenarios that cannot be achieved using annotations. This article is designed to demonstrate how to use the fluent API to configure properties.

    The code first fluent API is most commonly accessed by overriding the  OnModelCreating method on your derived  DbContext. The following samples are designed to show how to do various tasks with the fluent api and allow you to copy the code out and customize it to suit your model, if you wish to see the model that they can be used with as-is then it is provided at the end of this article.

    在code first 中的DbContext 自己的实现类中,重载方法“ OnModelCreating”,在方法体中添加如“modelBuilder.Entity<Department>().HasKey(t => new { t.DepartmentID, t.Name });

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Department>().HasKey(t => new { t.DepartmentID, t.Name });
                base.OnModelCreating(modelBuilder);
            }


     

    参考文献:

    http://msdn.microsoft.com/en-us/data/JJ591617.aspx#1.2

  • 相关阅读:
    vue使用talkIngData统计
    vue项目中使用百度统计
    vue的指令修饰符
    提问:
    整理心情再投入下一个阶段
    CSS写三角形
    单行文本和多行文本超出隐藏
    清除浮动的方法
    用JS表示斐波拉契数列
    vue中使用动态挂载和懒加载,实现点击导航栏菜单弹出不同弹框
  • 原文地址:https://www.cnblogs.com/hobinly/p/7493576.html
Copyright © 2011-2022 走看看