0

Разбираюсь потихоньку с Entity. На этот раз проблема в добавлении записи в таблицу Mysql. Таблица :

CREATE TABLE `cashaccounts` (
`orderKlient` varchar(45) NOT NULL,
`CA_USD` decimal(10,2) NOT NULL,
`CA_EUR` decimal(10,2) NOT NULL,
`CA_GBP` decimal(10,2) NOT NULL,
`CA_SGD` decimal(10,2) NOT NULL,
`CA_AUD` decimal(10,2) NOT NULL,
`CashAllocation` decimal(10,2) NOT NULL,
`DATEH` datetime NOT NULL
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8

Сущность в edmx (подход DataBaseFirst) :

 public partial class cashaccounts
 {
    public string orderKlient { get; set; }
    public decimal CA_USD { get; set; }
    public decimal CA_EUR { get; set; }
    public decimal CA_GBP { get; set; }
    public decimal CA_SGD { get; set; }
    public decimal CA_AUD { get; set; }
    public decimal CashAllocation { get; set; }
    public System.DateTime DATEH { get; set; }
 }

И сам код, добавляющий новую строку в таблицу :

public void NewCashHistory()
    {
        var newRow = new cashaccounts();
        newRow.orderKlient = order;
        newRow.CashAllocation = cashallocation;
        newRow.CA_AUD = 11.22M;
        newRow.CA_EUR = 11.22M;
        newRow.CA_GBP = 11.22M;
        newRow.CA_SGD = 11.22M;
        newRow.CA_USD = 11.22M;
        newRow.DATEH = DateTime.Now;

        using (custodianhistoryEntities1 Context = new custodianhistoryEntities1())
        {
            Context.cashaccounts.Add(newRow);
            Context.SaveChanges();  // тут ошибка
        };
    }

При попытке сохранить изменения вылетает ошибка :

Необработанное исключение типа "System.Data.Entity.Infrastructure.DbUpdateException" в EntityFramework.dll

Дополнительные сведения: При обновлении записей возникла ошибка. Дополнительные сведения приведены во внутреннем исключении.

Подозреваю что дело в формате даты, так ил это? Кто сталкивался, подскажите как исправить?

Больше сведений об исключении :

StackTrace: в System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() в System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator ut) в System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func2 updateFunction) в System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() в System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() в System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) в System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) в System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27() в System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func1 operation) в System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) в System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) в System.Data.Entity.Internal.InternalContext.SaveChanges() InnerException: ErrorCode=-2147467259 HResult=-2147467259 Message=You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT cashaccounts.orderKlient, cashaccounts.CA_USD, cashaccounts`.' at line 1 Number=1064 Source=MySql.Data

1
  • Комментарии не предназначены для расширенной дискуссии; разговор перемещён в чат.
    – user177221
    7 сен 2017 в 11:54

1 ответ 1

1

Я работал с Microsoft.EntityFrameworkCore и Pomelo.EntityFrameworkCore.MySql.

1) Создал обычный консольный проект.

2) Открыл Package Manager Console и установил нужные пакеты

PM> Install-Package Pomelo.EntityFrameworkCore.MySql

PM> Install-Package Microsoft.EntityFrameworkCore.Tools

PM> Install-Package Pomelo.EntityFrameworkCore.MySql.Design

3) И когда я попытался сделать скефолдинг получил жалобу на отсутствие первичного ключа PM> Scaffold-DbContext "Server=localhost;User Id=root;Password=1234;Database=test_schema" Pomelo.EntityFrameworkCore.MySql -OutputDir Models

Unable to identify the primary key for table 'cashaccounts'. rosoft.EntityFrameworkCore.Scaffolding.RelationalScaffoldingModelFactory[7] Unable to identify the primary key for table 'cashaccounts'.

4) добавил первичный ключ в вашу таблицу

5) делаю скефолдинг

PM> Scaffold-DbContext "Server=localhost;User Id=root;Password=1234;Database=test_schema" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force

6) в папке Models создается класс сущности

public partial class Cashaccounts
{
    public int Id { get; set; }
    public decimal CaAud { get; set; }
    public decimal CaEur { get; set; }
    public decimal CaGbp { get; set; }
    public decimal CaSgd { get; set; }
    public decimal CaUsd { get; set; }
    public decimal CashAllocation { get; set; }
    public DateTime Dateh { get; set; }
    public string OrderKlient { get; set; }
}

и такой вот класс контекста

public partial class test_schemaContext : DbContext
{
    public virtual DbSet<Cashaccounts> Cashaccounts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseMySql(@"Server=localhost;User Id=root;Password=1234;Database=test_schema");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Cashaccounts>(entity =>
        {
            entity.ToTable("cashaccounts");

            entity.Property(e => e.Id).HasColumnType("mediumint(9)");

            entity.Property(e => e.CaAud)
                .HasColumnName("CA_AUD")
                .HasColumnType("decimal(10,2)");

            entity.Property(e => e.CaEur)
                .HasColumnName("CA_EUR")
                .HasColumnType("decimal(10,2)");

            entity.Property(e => e.CaGbp)
                .HasColumnName("CA_GBP")
                .HasColumnType("decimal(10,2)");

            entity.Property(e => e.CaSgd)
                .HasColumnName("CA_SGD")
                .HasColumnType("decimal(10,2)");

            entity.Property(e => e.CaUsd)
                .HasColumnName("CA_USD")
                .HasColumnType("decimal(10,2)");

            entity.Property(e => e.CashAllocation).HasColumnType("decimal(10,2)");

            entity.Property(e => e.Dateh)
                .HasColumnName("DATEH")
                .HasColumnType("datetime");

            entity.Property(e => e.OrderKlient)
                .IsRequired()
                .HasColumnName("orderKlient")
                .HasColumnType("varchar(45)");
        });
    }
}

Ну, а дальше дело техники

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("ConsoleTest1");

        using (test_schemaContext context = new test_schemaContext())
        {
            //AddAccount(context);

            ShowAccounts(context);
        };

        Console.ReadLine();
    }

    private static void AddAccount(test_schemaContext context)
    {
        var newRow = new Cashaccounts();
        newRow.CaAud = 11.22M;
        newRow.CaEur = 11.22M;
        newRow.CaGbp = 11.22M;
        newRow.CaSgd = 11.22M;
        newRow.CaUsd = 11.22M;
        newRow.Dateh = DateTime.Now;
        newRow.CashAllocation = 11.22M;
        newRow.OrderKlient = "TestClient";

        context.Cashaccounts.Add(newRow);
        context.SaveChanges();
    }

    private static void ShowAccounts(test_schemaContext context)
    {
        var accs = context.Cashaccounts.ToList();

        accs.ForEach(a => Console.WriteLine($"{a.Id}-{a.OrderKlient}:{a.Dateh}"));
    }

}

И вуаля все работает.

2

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.