Tech Off Post

Single Post Permalink

View Thread: Question about EF
  • User profile image

    Maybe I'm missing something here, but is there any way to update the primary key of an entity?

    I know that PKs should be immutable, but I'm working with an existing database where some of the tables are set up with PKs that routinely change. If EF doesn't support this, then EF is pretty much a non-starter.

    Here's my test code. The database table is a made up one for testing EF.

    Module Module1
        Sub Main()
            Dim p As New Paradev()
            Dim c = Aggregate r In p.CustomerOrders Into Count()
            Console.Out.WriteLine("Count is {0}", c)
            Dim first = p.CustomerOrders.First()
            first.Amount = 12345
        End Sub
    End Module
    Public Class CustomerOrder
        Public Property Name As String
        Public Property OrderDate As Date?
        Public Property Amount As Decimal?
    End Class
    Public Class Paradev
        Inherits DbContext
        Public Property CustomerOrders As DbSet(Of CustomerOrder)
        Protected Overrides Sub OnModelCreating(modelBuilder As System.Data.Entity.DbModelBuilder)
            modelBuilder.Entity(Of CustomerOrder).HasKey(Function(t) New With {t.Name, t.OrderDate, t.Amount})
            modelBuilder.Entity(Of CustomerOrder).Property(Function(t) t.Name).HasColumnName("NAME")
            modelBuilder.Entity(Of CustomerOrder).Property(Function(t) t.Amount).HasColumnName("AMT")
            modelBuilder.Entity(Of CustomerOrder).Property(Function(t) t.OrderDate).HasColumnName("DT")
            modelBuilder.Entity(Of CustomerOrder)().ToTable("CUSTOMER_ORDERS", "SSP01953")
        End Sub
    End Class