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

been looking around and i just cant seem to figure out what is wrong.

Currently i’m trying to update my database with a new highscore when ever the player dies. But it keeps throwing that exception at me, no matter what i choose to try and save.

Code:

 HighScore hs = new HighScore();
            var id = from i in db.HighScores
                     orderby i.ID descending
                     select i;
            int newId = 0;

            if (id.Count() == 0)
            {
                newId = 1;
            }
            else
            {
                newId = id.First().ID + 1;
            }
        hs.ID = 6; //I just hardcoded in 6 to make sure i wasent because of the newId      //thing, and i have checked if theres already something on the sixths spot as well.
            hs.UserHighscore = 100;
            hs.HighscoreUsername = "test";
            hs.GameID = 1;
            db.HighScores.AddObject(hs);
            db.SaveChanges();

I’ve checked, again and again, and i just cant seem to figure out what the problem is.

Any help would be appriciated.

The exception:

System.Data.UpdateException was unhandled
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
       at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
       at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
       at System.Data.Objects.ObjectContext.SaveChanges()
       at MatematikSpilMenu.SaveBunniesSceen.SaveHighscore() in MatematikSpilMenuSaveBunniesSceen.cs:line 173
       at MatematikSpilMenu.SaveBunniesSceen.Update(GameTime gameTime, Boolean otherScreenIsActive, Boolean coveredByOtherScreens) in C:UsersEtarnalazure-Aliendocumentsvisual studio 2010ProjectsMatematikSpilMenuMatematikSpilMenuMatematikSpilMenuSaveBunniesSceen.cs:line 110
       at MatematikSpilMenu.ScreenManager.Update(GameTime gameTime) in MatematikSpilMenuScreenManager.cs:line 101
       at Microsoft.Xna.Framework.Game.Update(GameTime gameTime)
       at Microsoft.Xna.Framework.Game.Tick()
       at Microsoft.Xna.Framework.Game.HostIdle(Object sender, EventArgs e)
       at Microsoft.Xna.Framework.GameHost.OnIdle()
       at Microsoft.Xna.Framework.WindowsGameHost.RunOneFrame()
       at Microsoft.Xna.Framework.WindowsGameHost.ApplicationIdle(Object sender, EventArgs e)
       at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle(Int32 grfidlef)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Microsoft.Xna.Framework.WindowsGameHost.Run()
       at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
       at Microsoft.Xna.Framework.Game.Run()
       at MatematikSpilMenu.Program.Main() in MatematikSpilMenuGame1.cs:line 120
  InnerException: System.Data.EntityCommandCompilationException
       Message=An error occurred while preparing the command definition. See the inner exception for details.
       Source=System.Data.Entity
       StackTrace:
            at System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
            at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
            at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
            at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
       InnerException: System.NotSupportedException
            Message=Server-generated keys and server-generated values are not supported by SQL Server Compact.
            Source=System.Data.SqlServerCe.Entity
            StackTrace:
                 at System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateReturningSql(StringBuilder commandText, DbModificationCommandTree tree, ExpressionTranslator translator, DbExpression returning)
                 at System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree tree, List`1& parameters, Boolean isLocalProvider)
                 at System.Data.SqlServerCe.SqlGen.SqlGenerator.GenerateSql(DbCommandTree tree, List`1& parameters, CommandType& commandType, Boolean isLocalProvider)
                 at System.Data.SqlServerCe.SqlCeProviderServices.CreateCommand(DbProviderManifest providerManifest, DbCommandTree commandTree)
                 at System.Data.SqlServerCe.SqlCeProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
                 at System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)
                 at System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)
                 at System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
            InnerException: 

Всем привет, 3 вопроса:

1.такая проблема. EF последняя версия. Visual Studio. Создал простую базу данных. Создал модель. Создал таблицу. Через код добавляю в таблицу данные. Одну строчку он добавляет. Но вот как впишу еще одну например с названием «bu2» то уже ошибка на моменте db.SaveChanges();

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

SqlException: Violation of PRIMARY KEY constraint ‘PK__Buffet__3214EC070BE69470’. Cannot insert duplicate key in object ‘dbo.Buffet’. The duplicate key value is (0).
The statement has been terminated.

2.Даже когда на одной строке срабатывает, я открываю таблицу, там нету записанных данных, получается что база данных ничего не записывает?

3.Почему в db. я уже нахожу свою таблицу во множественном числе с буквой s на конце?

class Program
{
    static void Main(string[] args)
    {
        Database1Entities db = new Database1Entities();

        var query = from t in db.Buffets select t;



        Buffet bu1 = new Buffet { MarketCap = 651616556, Index = "fesfs", 
        TotalDebt = 56156 };

        db.Buffets.Add(bu1);

        db.SaveChanges();

        foreach (var item in query)
        {
            Console.WriteLine(item.MarketCap);
        }

        Console.ReadKey();
    }
}

Вот так решается проблема, не хочет автоматом Id прописывать, но второй
вопрос остается все еще открытым.

static void Main(string[] args)
{
    using (Database1Entities db1 = new Database1Entities())
    {
        Buffet bu1 = new Buffet { Id = 0, MarketCap = 651616556, Index = 
       "SP500", TotalDebt = 79994};
        Buffet bu2 = new Buffet { Id = 1, MarketCap = 657145, Index = 
       "Dow30", TotalDebt = 582166 };
        Buffet bu3 = new Buffet { Id = 2, MarketCap = 157212, Index = 
         "NASDAQ", TotalDebt = 1298974 };
        db1.Buffets.Add(bu1);
        db1.Buffets.Add(bu2);
        db1.Buffets.Add(bu3);

        db1.SaveChanges();

        var query = from t in db1.Buffets select t;

        foreach (var item in query)
        {
            Console.WriteLine(item.MarketCap);
            Console.WriteLine(item.TotalDebt);
        }
    }
    Console.ReadKey();
}

покажите как у вас объявлен Buffet.

PashaPash Если вы вот это имеете ввиду, то вот так:

 public virtual DbSet<Buffet> Buffets { get; set; }

Автоматом при создание модели генерирует.

что проверяете именно в той базе?

Захожу в таблицу Buffet, а там всюду null, после отладки не сохраняются данные.

как именно у вас база подключена?

Она подключена обычно:) не знаю как точно ответить. Создал простую базу в VS, создал модель. На ней зеленая розетка, но при запуске отладки загорается крестик красные, может она просто отключается на отладку. Нашел тут на форму ответ, что нужно поставить if newer в свойствах базы данных. Я та понял это в свойствах базы данных, у меня рус. версия. Как я понял это связано с «Копировать в выходной каталог», но переключая там на разные вкладки снова ошибка на SaveChages().

Usaga,

Код

System.Data.Entity.Infrastructure.DbUpdateException не обработано
  HResult=-2146233087
  Message=При обновлении записей произошла ошибка. Подробные сведения см. во внутреннем исключении.
  Source=EntityFramework
  StackTrace:
       в System.Data.Entity.Internal.InternalContext.SaveChanges()
       в System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
       в System.Data.Entity.DbContext.SaveChanges()
       в Procat.MainWindow.Save_Click(Object sender, RoutedEventArgs e) в D:ProcatProcatMainWindow.xaml.cs:строка 71
       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       в System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       в System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       в System.Windows.Controls.Primitives.ButtonBase.OnClick()
       в System.Windows.Controls.Button.OnClick()
       в System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       в System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       в System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       в System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       в System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       в System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       в System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       в System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       в System.Windows.Input.InputManager.ProcessStagingArea()
       в System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       в System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       в System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       в System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       в System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       в MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       в System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
       в System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       в System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       в System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       в System.Windows.Application.RunDispatcher(Object ignore)
       в System.Windows.Application.RunInternal(Window window)
       в System.Windows.Application.Run(Window window)
       в System.Windows.Application.Run()
       в Procat.App.Main() в D:ProcatProcatobjDebugApp.g.cs:строка 0
       в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       в System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2146233087
       Message=При обновлении записей произошла ошибка. Подробные сведения см. во внутреннем исключении.
       Source=System.Data.Entity
       StackTrace:
            в System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
            в System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
            в System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
            в System.Data.Entity.Internal.InternalContext.SaveChanges()
       InnerException: 
            Class=14
            ErrorCode=-2146232060
            HResult=-2146232060
            LineNumber=1
            Message=Violation of PRIMARY KEY constraint 'PK__tmp_ms_x__3214EC0704A01891'. Cannot insert duplicate key in object 'dbo.Procatoff'. The duplicate key value is (0).
The statement has been terminated.
            Number=2627
            Procedure=""
            Server=(LocalDB)MSSQLLocalDB
            Source=.Net SqlClient Data Provider
            State=1
            StackTrace:
                 в System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                 в System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                 в System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                 в System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
                 в System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
                 в System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
                 в System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
                 в System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
                 в System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                 в System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
                 в System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
            InnerException:



0



У меня проблема, я только начал изучать модель EF, и я остаюсь в одной точке в течение некоторого времени. Я получил такую ошибку:

» при обновлении записей произошла ошибка. См. внутреннее исключение для деталей»

Я создал простой модели, схемы, создание базы данных и написал простой код на C#, чтобы добавить только одну строку в таблице, но ошибка появляется все время.

Я публикую скриншот с диаграммой / сгенерированной DLL / простой основной / и ошибка метания

model and stuff

Ссылка для большего размера:http://i.imgur.com/bKGc4wv.png

7 ответов


повернуть Pluralization On. Проблема в том, что вы моделируете объект, используя единственное имя (Pupil) соглашение, в то время как в вашей базе данных вы используете несколько имен Pupils С s.

обновление

этой в должности показывает, как вы можете включить его или выключить.
Некоторые соответствующие выдержки из этого поста:

для включения и выключения плюрализации

  • в меню Сервис выберите Опции.

  • в диалоговом окне Параметры разверните узел базы данных.
    Примечание: выберите Показать все параметры, если узел инструменты базы данных не отображается.

  • Нажмите O/R Designer.

  • установите Плюрализацию имен в Enabled = False для установки конструктора O/R, чтобы он не изменял имена классов.

  • установите Плюрализацию имен в Enabled = True, чтобы применить правила плюрализации к именам классов объекты, добавленные в реляционный конструктор объектов.

обновление 2

но обратите внимание, что вы должны избегать множественных имен.
Вы можете читать здесь как это сделать (я приведу его здесь, на случай, если ссылка будет нарушена).

(…) при первом подходе к коду Entity Framework таблицы базы данных создаются из классов моделей. Обычно Entity Framework создает таблицы с несколькими именами. это означает, что если у вас есть класс модели PhoneNumber, Entity framework создаст таблицу для этого класса под названием «PhoneNumbers». Если вы хотите избежать множественного имени и хотите единственное имя, как клиент , вы можете сделать это так
В вашем классе DBContext переопределите метод «OnModelCreating» следующим образом (…)

enter image description here

(…) переопределение этого метода позволит избежать создания таблиц с множественными именами. Теперь он создаст Таблица называется «PhoneNumber», а не» PhoneNumbers»(…)


Это может быть причиной преобразования данных из .net в sql. например, ошибка преобразования datetime.

вообще это не точная ошибка. вы можете увидеть точную ошибку в watch at exception.Свойство innerexception.InnerException — > ResultView.

для меня это была пустая ссылка на столбец datetime


Я столкнулся с той же ошибкой:

» при обновлении записей произошла ошибка. См. внутреннее исключение
для детали»

просто удалить и заново создать *.файл edmx. Это сработало для меня. ошибка исчезнет


недавно у меня была эта проблема.
Это произошло, потому что разрешения пользовательской базы данных.
проверьте разрешения базы данных пользователя, возможно, у пользователя нет разрешения на запись в БД.


я столкнулся с той же проблемой, и не вышеперечисленные решения помогли мне. В моем Web Api 2 проект, я фактически обновил свою базу данных и разместил unique constraint на SQL table column. это действительно было причиной проблемы. Просто проверка повторяющихся значений столбцов перед вставкой помогла мне устранить проблему!


для записи у меня была эта проблема и была глупая ошибка с моей стороны. Моей проблемой было несоответствие типов данных.
Тип данных в таблице базы данных и классах C# должен быть одинаковым……


моя проблема заключалась в том, что идентификатор таблицы не является AUTO_INCREMENT, и я пытался добавить диапазон.


#c# #asp.net-mvc-5 #relational-database #entity-framework-migrations

#c# #asp.net-mvc-5 #реляционная база данных #entity-framework-миграции

Вопрос:

Недавно я пытался удалить поле из своей базы данных, и теперь каждый раз, когда я пытаюсь запустить Update-database , я получаю эту ошибку:

При обновлении записей произошла ошибка. Подробности см. Во внутреннем исключении.

Полное описание ошибки здесь
Таблица Sql

Я использовал

 Enable-Migrations -ContextTypeName ArtistDatabase.Models.ArtistDBContext 

Add-Migration Initial 

Update-database.
  

Artist.Cs

 using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace ArtistDatabase.Models
{
public class Artist
{
    public int ID { get; set; }
    //----------------------------------------------------------------------------------------------
    [Required,StringLength(60, MinimumLength = 3), Display(Name = "Artist")]
    public string Name { get; set; }
    //----------------------------------------------------------------------------------------------
    [DataType(DataType.ImageUrl)]
    public string Picture { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = "Date of Birth"),DataType(DataType.Date),DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime BirthDate { get; set; }
    //----------------------------------------------------------------------------------------------
    [Required,StringLength(30)]
    public string Nationality { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = "Art Style/Movement")]
    public string ArtStyle { get; set; }
    //----------------------------------------------------------------------------------------------
    [DataType(DataType.MultilineText)]
    public string Info { get; set; }
    //----------------------------------------------------------------------------------------------
    [RegularExpression(@"^[A-Z] [a-zA-Z''-'s]*$")]
    [StringLength(5)]
    public string Rating { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = "Famous work: "),DataType(DataType.ImageUrl)]
    public string Artwork1 { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = " "), DataType(DataType.ImageUrl)]
    public string Artwork2 { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = " "), DataType(DataType.ImageUrl)]
    public string Artwork3 { get; set; }
}

public class ArtistDBContext : DbContext
{
    public DbSet<Artist> Artists { get; set; }
}
}
  

Конфигурация.Cs (начальный метод)

  namespace ArtistDatabase.Migrations
{
using Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;

internal sealed class Configuration : DbMigrationsConfiguration<ArtistDatabase.Models.ArtistDBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(ArtistDatabase.Models.ArtistDBContext context)
    {
        context.Artists.AddOrUpdate(i => i.Name,
            new Artist
            {
                Name = "Pablo Ruiz y Picasso",
                Picture = "http://a5.files.biography.com/image/upload/c_fit,cs_srgb,dpr_1.0,h_1200,q_80,w_1200/MTE1ODA0OTcxNzU0MDk2MTQx.jpg",
                BirthDate = DateTime.Parse("25-10-1881"),
                Nationality = "Spanish",
                ArtStyle = "Cubism, Surrealism",
                Info = "Picasso was a Spanish painter, sculptor and ceramicist, among other things. He spent most of his adult life in France, "  
                "and is regarding as one of the greatest and most influential artists of the 20th century. He is known as co-founding of the"  
                " 'Cubist' movement; the invention of constructed sculpture, also being the co-inventor of collage, and for the wide variety"  
                " of styles that he helped develop and explore. Picasso, Henri Matisse and Marcel Duchamp are regarded as the three artists"  
                " who most defined the revolutionary developments in the plastic arts in the opening decades of the 20th century, responsible"  
                " for significant developments in painting, sculpture, printmaking and ceramics. Picasso demonstrated extraordinary artistic"  
                " talent in his early years, painting in a naturalistic manner through his childhood and adolescence.During the first decade"  
                " of the 20th century, his style changed as he experimented with different theories, techniques, and ideas.His work is often"  
                " categorized into periods.While the names of many of his later periods are debated, the most commonly accepted periods in his"  
                " work are the Blue Period(1901–1904), the Rose Period(1904–1906), the African - influenced Period(1907–1909),"  
                " Analytic Cubism(1909–1912),and Synthetic Cubism(1912–1919),also referred to as the Crystal period. Exceptionally prolific"  
                " throughout the course of his long life, Picasso achieved universal renown and immense fortune for his revolutionary artistic"  
                " accomplishments, and became one of the best - known figures in 20th - century art.",
                Rating = "",
                Artwork1 = "https://mocochocodotcom.files.wordpress.com/2013/11/how-to-recognize-painters-by-their-work-picasso2.jpg",
                Artwork2 = "http://paintingandframe.com/uploadpic/pablo_picasso/big/les_demoiselles_d_avignon_c_1907.jpg",
                Artwork3 = "http://www.themost10.com/wp-content/uploads/2012/03/Blue-Nude-By-Pablo-Picasso.jpg?09df94"
            },

            new Artist
            {
                Name = "Leonardo da Vinci",
                Picture = "http://www.leonardodavinci.net/images/leonardo-da-vinci.jpg",
                BirthDate = DateTime.Parse("15-04-1452"),
                Nationality = "Italian",
                ArtStyle = "High Renaissance",
                Info = "Leonardo di ser Piero da Vinci was an Italian polymath whose areas of interest included invention, painting,"  
                " sculpting, architecture, science, music, mathematics, engineering, literature, anatomy, geology, astronomy, botany, writing, history,"  
                " and cartography. He has been variously called the father of palaeontology, ichnology, and architecture, and is widely considered one"  
                " of the greatest painters of all time. Sometimes credited with the inventions of the parachute, helicopter and tank, he epitomised"  
                " the Renaissance humanist ideal.Many historians and scholars regard Leonardo as the prime exemplar of the 'Universal Genius' or "  
                "'Renaissance Man', an individual of 'unquenchable curiosity' and 'feverishly inventive imagination'. According to art historian Helen"  
                " Gardner, the scope and depth of his interests were without precedent in recorded history, and 'his mind and personality seem to us"  
                " superhuman, while the man himself mysterious and remote'. Marco Rosci notes that while there is much speculation regarding his life"  
                " and personality, his view of the world was logical rather than mysterious, and that the empirical methods he employed were unorthodox"  
                "for his time. Leonardo was, and is, renowned primarily as a painter. Among his works, the Mona Lisa is the most famous and most"  
                " parodied portrait and The Last Supper the most reproduced religious painting of all time, their fame approached only by Michelangelo's"  
                " The Creation of Adam. Leonardo's drawing of the Vitruvian Man is also regarded as a cultural icon, being reproduced on items as"  
                " varied as the euro coin, textbooks, and T-shirts. Perhaps fifteen of his paintings have survived. Nevertheless, these few works,"  
                " together with his notebooks, which contain drawings, scientific diagrams, and his thoughts on the nature of painting, compose a"  
                " contribution to later generations of artists rivalled only by that of his contemporary, Michelangelo.",
                Rating = "",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg/402px-Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg",
                Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/2/23/Leonardo_da_Vinci_-_Last_Supper_(copy)_-_WGA12732.jpg",
                Artwork3 = "http://blog.world-mysteries.com/wp-content/uploads/2011/01/vitruvian_man_mixed.jpg"
            },

            new Artist
            {
                Name = "Georgia O'Keeffe",
                Picture = "http://1874.img.pp.sohu.com.cn/images/blog/2008/11/16/20/26/11e4d90ce26g213.jpg",
                BirthDate = DateTime.Parse("15-11-1887"),
                Nationality = "American",
                ArtStyle = "American Modernism",
                Info = "Georgia Totto O'Keeffe was an American artist. She is best known for her paintings of enlarged flowers, New York skyscrapers,"  
                " and New Mexico landscapes. O'Keeffe has been recognized as the 'Mother of American modernism'. O'Keeffe studied at the School of the"  
                " Art Institute of Chicago from 1905 to 1906. In 1907, she attended the Art Students League in New York City, where she studied under"  
                " William Merritt Chase. In 1908, she won the League's William Merritt Chase still-life prize for her oil painting Dead Rabbit with"  
                " Copper Pot. Her prize was a scholarship to attend the League's outdoor summer school in Lake George, New York. While in the city"  
                " in 1908, O'Keeffe attended an exhibition of Rodin's watercolors at the gallery 291, owned by her future husband, photographer Alfred"  
                " Stieglitz. O'Keeffe abandoned the idea of pursuing a career as an artist in late 1908, claiming that she could never distinguish"  
                " herself as an artist within the mimetic tradition which had formed the basis of her art training. She took a job in Chicago as"  
                " a commercial artist. She did not paint for four years, and said that the smell of turpentine made her sick. She was inspired to"  
                " paint again in 1912, when she attended a class at the University of Virginia Summer School, where she was introduced to the innovative"  
                " ideas of Arthur Wesley Dow by Alon Bement. Dow encouraged artists to express themselves using line, color, and shading"  
                " harmoniously. From 1912-14, she taught art in the public schools in Amarillo in the Texas Panhandle. She attended Teachers College"  
                " of Columbia University from 1914–15, where she took classes from Dow, who greatly influenced O'Keeffe's thinking about the process of"  
                " making art. She served as a teaching assistant to Bement during the summers from 1913–16 and taught at Columbia College, Columbia,"  
                " South Carolina in late 1915, where she completed a series of highly innovative charcoal abstractions. After further course work at"  
                " Columbia in early 1916 and summer teaching for Bement, she took a job as head of the art department at West Texas State Normal College"  
                " from late 1916 to February 1918, the fledgling West Texas Aamp;M University in Canyon just south of Amarillo. While there, she often"  
                " visited the Palo Duro Canyon, making its forms a subject in her work.",
                Rating = "",
                Artwork1 = "http://www.georgiaokeeffe.net/images/paintings/rams-head.jpg",
                Artwork2 = "https://learnodo-newtonic.com/wp-content/uploads/2015/09/Red-Canna-1924-Georgia-OKeeffe.jpg",
                Artwork3 = "http://www.themasterpiececards.com/hs-fs/hub/40667/file-25876050-jpg/images/okeeffe_jack_2_from_nga-resized-600.jpg?t=1465250810631"
            },

            new Artist
            {
                Name = "Vincent van Gogh",
                Picture = "http://site.artsheaven.com/blog/wp-content/uploads/2015/10/vincent.jpg",
                BirthDate = DateTime.Parse("30-03-1853"),
                Nationality = "Dutch",
                ArtStyle = "Post-Impressionism",
                Info = "Vincent Willem van Gogh was a Dutch painter who is among the most famous and influential figures in the history of Western art."  
                " In just over a decade he created about 2100 artworks, including around 860 oil paintings, most of them in the last two years of his"  
                " life. They include landscapes, still lifes, portraits and self-portraits, and are characterised by bold, symbolic colours, and"  
                " dramatic, impulsive and highly expressive brushwork that contributed to the foundations of modern art. He sold only one painting"  
                " during his lifetime and became famous after his suicide at age 37, which followed years of poverty and mental illness. Van Gogh's"  
                " early works, mostly still lifes and depictions of peasant labourers, contain few signs of the vivid colour that distinguished his"  
                " later work. In 1886 he moved to Paris and discovered the French Impressionists. As his work developed he created a new approach to"  
                " still lifes and local landscapes. His paintings grew brighter in colour as he developed a style that became fully realised during his"  
                " stay in Arles in the south of France in 1888. He lived there in the Yellow House and, with the French artist Paul Gauguin, developed a"  
                " concept of colour that symbolised inner emotion. During this period he broadened his subject matter to include olive trees, cypresses,"  
                " wheat fields and sunflowers. In Nuenen, Van Gogh focused on painting and drawing. Working outside and very quickly, he completed"  
                " sketches and paintings of weavers and their cottages. In August 1884, Margot Begemann, a neighbour's daughter and ten years"  
                " his senior, began joining him on his painting forays; she fell in love, and he reciprocated, though less enthusiastically. They"  
                " decided to marry, but the idea was opposed by both families, following which Margot took an overdose of strychnine. She was saved"  
                " when Van Gogh rushed her to a nearby hospital. On 26 March 1885, his father died of a heart attack. Van Gogh painted several"  
                "groups of still lifes in 1885. During his two - year stay in Nuenen, he completed numerous drawings and watercolours, and nearly"  
                "200 oil paintings.His palette consisted mainly of sombre earth tones, particularly dark brown, and showed no sign of the vivid colours"  
                "that distinguish his later work.Considered a madman and a failure in his lifetime,Van Gogh exists in the public imagination as the"  
                "quintessential misunderstood genius, the artist 'where discourses on madness and creativity converge'.His reputation began to grow"  
                "in the early 20th century as elements of his painting style came to be incorporated by the Fauves and German Expressionists.He attained"  
                "widespread critical, commercial and popular success over the ensuing decades, and is remembered as an important but tragic painter,"  
                "whose troubled personality typifies the romantic ideal of the tortured artist.",
                Rating = "",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/9/94/Starry_Night_Over_the_Rhone.jpg",
                Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Vincent_van_Gogh_-_De_slaapkamer_-_Google_Art_Project.jpg/1280px-Vincent_van_Gogh_-_De_slaapkamer_-_Google_Art_Project.jpg",
                Artwork3 = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/Vincent_Willem_van_Gogh_128.jpg/175px-Vincent_Willem_van_Gogh_128.jpg"
            }

        );
    }
}
}
  

Комментарии:

1. Ну, что эти внутренние исключения говорят вам о том, что сообщение об ошибке просит вас проверить?

2. @marc_s Мои извинения, я не знал, где искать, но при проверке я обнаружил следующее: «Преобразование типа данных datetime2 в тип данных datetime привело к значению вне диапазона».

3. Это может произойти, если вы не присвоите значение полю даты и времени, когда поле не принимает нулевые значения.

4. @Tarzan Разве этот формат не подойдет? ‘Дата рождения = дата-время. Синтаксический анализ («25-10-1881»), ‘

5. Неясно: невозможно воспроизвести, все даты указаны позже 1 января 1753 года.

Ответ №1:

Эта строка вызывает ошибку, поскольку строка не распознается как допустимая дата-время.

 BirthDate = DateTime.Parse("25-10-1881")
  

Решение состоит в том, чтобы переписать строку с помощью ParseExtract следующим образом.

 BirthDate = DateTime.ParseExact("25-10-1881", "dd-MM-yyyy", null);
  

Кроме того, убедитесь, что поле SQL Server допускает значения, которые вы пытаетесь сохранить.

Комментарии:

1. Я только что попробовал это, и все равно ничего, то же исключение «вне диапазона».

2. Можете ли вы опубликовать трассировку стека, чтобы мы могли увидеть больше информации об ошибке?

3. Вот изображение полной ошибки i.stack.imgur.com/wP8M3.png .

4. Внутреннее исключение является SQLException, поэтому оно генерируется поставщиком SqlClient. Другими словами, ошибка генерируется базой данных. Тип данных SQL Server datetime способен хранить даты в диапазоне от 1753-01-01 до 9999-12-31. Тип данных datetime2, который можно хранить, — от 0001-01-01 до 9999-12-31. Какой тип данных представляет собой столбец в таблице SQL Server?

5. Дата рождения в таблице SQL server — это дата-время. Измените его на datetime2 .

  • При обновлении есет произошла ошибка
  • При обновлении драйверов видеокарты выдает ошибку
  • При обновлении драйверов nvidia происходит ошибка
  • При обновлении дота два произошла ошибка недопустимая конфигурация приложения
  • При обновлении дота 2 произошла ошибка файлы обновления повреждены