Translating Insert into select to Entity Framework 6

c# entity-framework entity-framework-6 sql sql-server

Question

I want to create multiple sequential number series The serial number would look like - e.g.

M1-00000001 M2-00000001 M1-00000002 M3-00000001 M2-00000002 ...

CREATE TABLE [dbo].[SerialNumber](
    [Id] [int] NOT NULL,
    [MachineId] [nchar](10) NOT NULL,
    [Snr] [int] NOT NULL,
 CONSTRAINT [PK_SerialNumber] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY]

I then use this query to create a new serial number

DECLARE @machine_id AS NCHAR(10)
SET @machine_id = 'M2'
INSERT INTO SerialNumber (MachineId,Snr)

SELECT @machine_id ,IIF(MAX(Snr) is not null,MAX(SNR)+1,1)
from SerialNumber
where MachineId=@machine_id

How would I do this in Entity Framework 6.1.3?

EDIT: I rewrote the whole question, don't know it you are suppose to do that, but someone will probably tell me if it's considered bad...

1
1
12/19/2016 3:15:34 PM

Accepted Answer

Edited after comments: This requires DbContext to be properly set up with a SerialNumbers property that represents the SerialNumber table. The SerialNumber objects are represented by the following class:

public class SerialNumber
{
    public int Id {get;set;} //Added after edit
    public string MachineId {get;set;}
    public int Snr {get;set;} //I assume it is a nullable int
}

and then some code similar to this should do the job:

public void AddSerial(string machineId)
{
    using (var context = new MyDbContext())
    {
        int max = context.SerialNumbers
            .Where(sn => sn.MachineId  == machineId)
            .Select(sn => sn.Snr)
            .DefaultIfEmpty(0)
            .Max(); //Extra clauses added after edit
        max++;
        context.SerialNumbers.Add(new SerialNumber{ MachineId = machineId, Snr = max});
        context.SaveChanges();
    }
}
2
12/19/2016 12:24:02 PM

Popular Answer

Entity Framework in an ORM, so you must create an object and link to your database, as follow:

You must:

  • have a class named SerialNumber
  • map with underlyng database table
  • persist your object in a DBContext

Here you can find a guide to use Entity Framework.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow