使用EF 6在本地SQL数据库中插入记录时遇到问题

问题描述 投票:0回答:1

我是一名学生开发人员,正在尝试开发一个小的数据库客户端系统,以便为经营一家小型企业的朋友注册和列出客户端。我认为这对我来说是一个绝佳的机会,可以尝试将我正在研究的东西变成可以使用的真实东西,即使它只是具有基本功能。

该程序在我的项目中使用本地数据库。我使用Windows窗体,带有EF6的.NET Framework 4.7.2,我的数据库是基于服务的数据库,您可以在Visual Studio中添加它。

我创建了一个应该注册客户端的表单,但是当我单击按钮时,即使SQL插入运行得很好,它也不会在数据库中插入值?数据库设置为ID列为自动递增,因此我只绕过了在代码中设置任何ID的步骤,因为数据库应该自动生成它,对吗?

这是使用一些测试值运行时的SQL输出:

Opened connection at 17/03/2020 17:30:34 -03:00

SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE t.TABLE_SCHEMA + '.' + t.TABLE_NAME IN ('dbo.Clientes')
    OR t.TABLE_NAME = 'EdmMetadata'
-- Executing at 17/03/2020 17:30:34 -03:00
-- Completed in 39 ms with result: 1

Closed connection at 17/03/2020 17:30:34 -03:00
"ZyonCliente.exe" (CLR v4.0.30319: ZyonCliente.exe): Carregado "C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll". Carregamento de símbolos ignorado. O módulo está otimizado e a opção do depurador 'Apenas Meu Código' está habilitada.
Opened connection at 17/03/2020 17:30:35 -03:00
SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[__MigrationHistory] AS [Extent1]
        WHERE [Extent1].[ContextKey] = @p__linq__0
    )  AS [GroupBy1]
-- p__linq__0: 'ZyonCliente1.DAL.ContextoBancoDeDados' (Type = String, Size = 4000)
-- Executing at 17/03/2020 17:30:35 -03:00
-- Failed in 13 ms with error: Invalid object name 'dbo.__MigrationHistory'.

Closed connection at 17/03/2020 17:30:35 -03:00
Opened connection at 17/03/2020 17:30:35 -03:00
SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[__MigrationHistory] AS [Extent1]
    )  AS [GroupBy1]
-- Executing at 17/03/2020 17:30:35 -03:00
-- Failed in 6 ms with error: Invalid object name 'dbo.__MigrationHistory'.

Closed connection at 17/03/2020 17:30:35 -03:00
"ZyonCliente.exe" (CLR v4.0.30319: ZyonCliente.exe): Carregado "EntityFrameworkDynamicProxies-EntityFramework". 
Opened connection at 17/03/2020 17:30:35 -03:00
Started transaction at 17/03/2020 17:30:35 -03:00
INSERT [dbo].[Clientes]([Nome], [Endereco], [Data_de_Nascimento], [Email], [Telefone])
VALUES (@0, @1, @2, @3, @4)
SELECT [ID]
FROM [dbo].[Clientes]
WHERE @@ROWCOUNT > 0 AND [ID] = scope_identity()
-- @0: 'testname' (Type = String, Size = 50)
-- @1: 'testaddress' (Type = String, Size = 100)
-- @2: '25/02/2020 17:30:17' (Type = DateTime2)
-- @3: 'testemail' (Type = String, Size = 80)
-- @4: 'testphone' (Type = String, Size = 50)
-- Executing at 17/03/2020 17:30:35 -03:00
-- Completed in 13 ms with result: SqlDataReader

Committed transaction at 17/03/2020 17:30:35 -03:00
Closed connection at 17/03/2020 17:30:35 -03:00

我已经尝试了几种不同的方法,甚至基于相同的数据库创建一个新项目,但是使用直接插入方法(而不是使用UnitsOfWork模式)以及使用BindingSource组件来插入值来插入值,什么也没做有效,我不知道为什么,因为似乎SQL正在运行,但是数据库只是拒绝更新?

这是按钮的代码:

private void button1_Click(object sender, EventArgs e)
{
    if (nomeTextBox.Text.Length == 0)
    {
        MessageBox.Show("Campo nome não pode estar vazio", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else
    {
        using (UnitsOfWork.UnitOfWork uow = new UnitsOfWork.UnitOfWork())
        {
            Cliente novocliente = new Cliente();
            novocliente.Nome = nomeTextBox.Text;
            novocliente.Endereco = nomeTextBox.Text;
            novocliente.Data_de_Nascimento = data_de_NascimentoDateTimePicker.Value;
            novocliente.Email = emailTextBox.Text;
            novocliente.Telefone = telefoneTextBox.Text;

            uow.Clientes.Add(novocliente);
            uow.Save();
            uow.Dispose();
        }
    }
}

我的UnitsOfWork代码为:

using System;
using ZyonCliente1.Model;

namespace ZyonCliente1.UnitsOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private ZyonCliente1.DAL.ContextoBancoDeDados _context;

        public UnitOfWork(ZyonCliente1.DAL.ContextoBancoDeDados context)
        {
            _context = context;
        }

        // Delete this default constructor if using an IoC container
        public UnitOfWork()
        {
            _context = new ZyonCliente1.DAL.ContextoBancoDeDados();
        }

        public Repositories.IClienteRepository Clientes
        {
            get { return new ZyonCliente1.Repositories.ClienteRepository(_context); }
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
        }
    }
}

还有我的DbContext

namespace ZyonCliente1.DAL
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Diagnostics;
    using ZyonCliente1.Model;
    //Database context file
    public partial class ContextoBancoDeDados : DbContext
    {
        public ContextoBancoDeDados()
            : base("name=ClientesModel")
        {
        }

        public virtual DbSet<Cliente> Clientes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.Log = (query) => Debug.Write(query);
        }
    }
}

也不确定是否需要,但这是我的实体类代码:

namespace ZyonCliente1.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

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

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [StringLength(100)]
        public string Endereco { get; set; }

        public DateTime? Data_de_Nascimento { get; set; }

        [StringLength(80)]
        public string Email { get; set; }

        [StringLength(50)]
        public string Telefone { get; set; }
    }
}

连接字符串:

<connectionStrings>
    <add name="ClientesModel" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ClientesDatabase.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
      providerName="System.Data.SqlClient" />
    <add name="ZyonCliente1.Properties.Settings.ClientesDatabaseConnectionString"
      connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ClientesDatabase.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

我也曾尝试在ID上使用[Key],但它也不起作用。我不确定是否需要共享其他内容(例如存储库等)的代码,因为它们只是UnitOfWork和存储库的普通模式,但是我可以在此处包括它们或为您共享我的项目的zip文件伙计们我真的不知所措,希望这里有人可以帮助我吗?我已经为此花了两天的时间。

我是一名学生开发人员,正在尝试开发一个小的数据库客户端系统,以便为经营一家小型企业的朋友注册和列出客户端。我认为这将是完美的...

sql database winforms entity-framework unit-of-work
1个回答
0
投票

首先,在研究工作单元,存储库等之前,先从最简单的事情开始将有所帮助。这只会使试图找出问题根源变得复杂。

© www.soinside.com 2019 - 2024. All rights reserved.