【问题标题】:Code-First generated code doesn't workCode-First 生成的代码不起作用
【发布时间】:2015-10-07 19:58:32
【问题描述】:

我首先使用数据库,在阅读了有关 Entity Framework 未来的信息之后,我决定先使用 VS2015 向导(数据库中的代码优先)转换为代码。

这是我的数据库图:

生成的代码没有像.edmx 那样映射表FinancialSell。但它没有进行任何配置。这是生成的代码:

public partial class XContext : DbContext
{
    public XContext()
        : base("name=XContext")
    {
    }

    public virtual DbSet<Financial> Financial { get; set; }
    public virtual DbSet<Sell> Sell { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
    }
}

[Table("Sell")]
public partial class Sell
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Sell()
    {
        Financial = new HashSet<Financial>();
    }

    public int ID { get; set; }

    public decimal Value { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Financial> Financial { get; set; }
}


[Table("Financial")]
public partial class Financial
{
    public int ID { get; set; }

    public DateTime Date { get; set; }

    public virtual Sell Sell { get; set; }
}

当我尝试使用简单的交互时:

 var sell = new Sell {Value = 1.00M};
        var financ = new Financial {Date = DateTime.Now, Sell = sell};

        using(var ctx = new XContext())
        {
            ctx.Financial.Add(financ);
            ctx.SaveChanges();

            Console.WriteLine("Ok Success!");
        }

引发异常:

保存不为其关系公开外键属性的实体时发生错误。 EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地处理保存时的异常。有关详细信息,请参阅 InnerException。

内部异常

列名“Sell_ID”无效。

【问题讨论】:

  • 好吧,InnerException 说什么?
  • 您只是在学习 edmx 课程吗?您可能需要为关系添加一些注释或流畅的代码。您可能想要对其进行逆向工程 (msdn.microsoft.com/en-us/data/jj200620.aspx)。
  • 第三个表的存在意味着多对多关系,但由于它看起来FinancialSell 表的主键链接到Financial 表的主键,每个Financial 记录只能映射到单个 Sell。如果这是所需的实现,您需要在 OnModelCreating 方法中添加一些配置,正如 Steve 提到的那样。
  • 您有virtual Sell Sell { get; set; },但没有int SellID { get; set; }。我相信您需要一个外键来链接表,而不仅仅是对它们的引用。
  • 它是根据 VS2015“数据库中的代码优先”向导生成的,我不知道如何使用 Fluent API 进行配置,我找到了示例但不适合我

标签: c# entity-framework entity-framework-6 code-first


【解决方案1】:

很抱歉,我不能用 C# 为你提供它 :) 但你应该可以找到一个合适的转换器。

Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Imports System.Data.Entity

Module Module1

    Sub Main()

    Dim sell = New Sell() With {
        .Value = 1D
    }
    Dim financ = New Financial() With {
        .[Date] = DateTime.Now,
        .Sell = sell
    }

    Using ctx = New XContext()
        ctx.Financials.Add(financ)
        ctx.FinancialSells.Add(New FinancialSell With {.Financial = financ, .Sell = sell})
        ctx.SaveChanges()

        Console.WriteLine("Ok Success!")
    End Using
End Sub

End Module
Partial Public Class XContext
Inherits DbContext

Public Sub New()
    'Recreates your database when it changes.
    Database.SetInitializer(Of XContext)(New DropCreateDatabaseIfModelChanges(Of XContext)())
    'MyBase.New("name=XContext")
End Sub

    Public Overridable Property Financials As DbSet(Of Financial)
    Public Overridable Property Sells As DbSet(Of Sell)
    Public Overridable Property FinancialSells As DbSet(Of FinancialSell)

    Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
    modelBuilder.Entity(Of FinancialSell)().HasRequired(Function(x) x.Sell).WithMany().WillCascadeOnDelete(False)
End Sub
End Class

<Table("Sell")>
Partial Public Class Sell
    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")>
    Public Sub New()
        Financial = New HashSet(Of Financial)()
    End Sub

    <Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(False)>
    Public Property ID As Integer
    Public Property Value As Decimal

    <System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")>
    Public Overridable Property Financial As ICollection(Of Financial)

End Class


<Table("Financial")>
Partial Public Class Financial
    <Key, Column(Order:=0), DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(False)>
    Public Property ID As Integer
    Public Property [Date] As DateTime
    <Column(Order:=1), ForeignKey("Sell")>
    Public Property SellID As Integer

    'Navigation Properties
    Public Overridable Property Sell As Sell

End Class

Partial Public Class FinancialSell
    <Key, Column(Order:=0), ForeignKey("Financial")>
    Public Property FinancialID As Integer
    <Key, Column(Order:=1), ForeignKey("Sell")>
    Public Property SellID As Integer

    'Navigation Properties
    Public Overridable Property Sell As Sell
    Public Overridable Property Financial As Financial
End Class

【讨论】:

  • 好的,但我需要保留数据库模型,应用程序正在生产中。我的表 FinancialSell 有一个 PK/FK,称为来自 Financial 的 ID 和 SellID 作为来自 Sell 的 FK
猜你喜欢
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多