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
Всем привет, 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().
Hello im kind new in MVC and i made a website so first i set a models and then from this model»with declaring the Db Context » i create a Controller and view from that and when i view it in website form it use to work fine and i can create data in the data base but then when i create everything i want to add a foreign key between the tables so i went the table and i added it and update but there is an error shows up when ever i try to add new data into the table so what should i do i hope that someone help me out this is some pic of the error and the table
this is the controller
the foreign key in the table
the code that send the error
public ActionResult Create([Bind(Include = "ID,UserID,KickOffDate")] UseCase useCase)
{
if (ModelState.IsValid)
{
db.UseCase.Add(useCase);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(useCase);
}
asked Aug 14, 2017 at 4:02
2
-
Delete your current migrations folder. (I trust you do not have any
expensive data) -
Change the name of your data table in the Config.Sys file.
-
Delete the table in App_Data
-
Then enable migrations.
-
Create a Add-Migration somename again
-
Then… Update-Data
answered Aug 14, 2017 at 13:45
alikulialikuli
5266 silver badges18 bronze badges
0
I think your problem will solve with the migration. For migrate do the following:
Open Package Manager Console
Tools –> Library Package Manager –> Package Manager Console
Then use the following commands
PM> Enable-migrations
PM> Add-migration Example // You can give a name instead of "Example"
PM> Update-database
answered Aug 14, 2017 at 4:12
Alsamil MehboobAlsamil Mehboob
3942 gold badges6 silver badges23 bronze badges
2
Hello im kind new in MVC and i made a website so first i set a models and then from this model»with declaring the Db Context » i create a Controller and view from that and when i view it in website form it use to work fine and i can create data in the data base but then when i create everything i want to add a foreign key between the tables so i went the table and i added it and update but there is an error shows up when ever i try to add new data into the table so what should i do i hope that someone help me out this is some pic of the error and the table
this is the controller
the foreign key in the table
the code that send the error
public ActionResult Create([Bind(Include = "ID,UserID,KickOffDate")] UseCase useCase)
{
if (ModelState.IsValid)
{
db.UseCase.Add(useCase);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(useCase);
}
asked Aug 14, 2017 at 4:02
2
-
Delete your current migrations folder. (I trust you do not have any
expensive data) -
Change the name of your data table in the Config.Sys file.
-
Delete the table in App_Data
-
Then enable migrations.
-
Create a Add-Migration somename again
-
Then… Update-Data
answered Aug 14, 2017 at 13:45
alikulialikuli
5266 silver badges18 bronze badges
0
I think your problem will solve with the migration. For migrate do the following:
Open Package Manager Console
Tools –> Library Package Manager –> Package Manager Console
Then use the following commands
PM> Enable-migrations
PM> Add-migration Example // You can give a name instead of "Example"
PM> Update-database
answered Aug 14, 2017 at 4:12
Alsamil MehboobAlsamil Mehboob
3942 gold badges6 silver badges23 bronze badges
2
Ошибка объекта данных «Ошибка при обновлении записей. Подробнее см. Внутреннее исключение».
Вопрос:
Я новичок в Entity Framework, я уже искал в google для этой проблемы, но ничего не нашел. Я получаю ошибку
При обновлении записей произошла ошибка. Подробнее см. Внутреннее исключение.
и когда я проверил внутреннее исключение, я вижу это
Невозможно вставить значение NULL в столбец “DOCNUM”, таблицу “TCPIDBV2.dbo.tbl_200_Dailyreport”; столбец не допускает нулей. INSERT терпит неудачу.
Но когда я проверил записи, которые я передал для сохранения в базе данных, в этом объекте есть значение, называемое “DOCNUM”,
Это мой код:
[Table("tbl_200_Dailyreport")]
public class tbl_200_Dailyreport
{
[Key]
[Required]
public long DOCNUM {get; set;}
public DateTime DAILYREPDATE {get; set;}
public string SECTION {get; set;}
public string REMARKS { get; set; }
public int? OPERATIONTIME { get; set; }
public int? PREPARATIONTIME { get; set; }
public int? STANDBYTIME { get; set; }
public int? MATERIALWAITING { get; set; }
public int? ASSISTTIME { get; set; }
public int? MAINTENANCETIME { get; set; }
public int? CLEANINGTIME { get; set; }
public bool? ISOVERTIME { get; set; }
public bool? ISLOCKED { get; set; }
public string SHIFT { get; set; }
public int? PRODTIME { get; set; }
public int? BREAKTIME { get; set; }
public double? TOTALCOLOR { get; set; }
public double? AVERAGECOLOR { get; set; }
}
При получении значения вышеприведенного здесь приведен код:
tbl_200_Dailyreport.DOCNUM = long.Parse(txtReferenceNo.Text);
tbl_200_Dailyreport.PRODTIME = Convert.ToInt32(txtProduction.Text);
tbl_200_Dailyreport.OPERATIONTIME = Convert.ToInt32(txtOperation.Text);
tbl_200_Dailyreport.PREPARATIONTIME = Convert.ToInt32(txtPreparation.Text);
tbl_200_Dailyreport.STANDBYTIME = Convert.ToInt32(txtStandby.Text);
tbl_200_Dailyreport.MAINTENANCETIME = Convert.ToInt32(txtMaintenance.Text);
tbl_200_Dailyreport.CLEANINGTIME = Convert.ToInt32(txtCleaning.Text);
tbl_200_Dailyreport.MATERIALWAITING = Convert.ToInt32(txtMaterial.Text);
tbl_200_Dailyreport.ASSISTTIME = Convert.ToInt32(txtAssist.Text);
tbl_200_Dailyreport.BREAKTIME = Convert.ToInt32(txtOthers.Text);
tbl_200_Dailyreport.DAILYREPDATE = dtpDailyReportDate.Value;
tbl_200_Dailyreport.SHIFT = cboShift.SelectedValue.ToString();
tbl_200_Dailyreport.ISOVERTIME = cbxOvertime.Checked;
tbl_200_Dailyreport.ISLOCKED = false;
tbl_200_Dailyreport.REMARKS = txtRemarks.Text;
if (!String.IsNullOrEmpty(cboSecDepartment.Text))
{
tbl_200_Dailyreport.SECTION = cboSecDepartment.SelectedValue.ToString();
}
else
{
var section = "0";
tbl_200_Dailyreport.SECTION = section;
}
Я разрешаю всем столбцам значение null, за исключением PK, называемого “DOCNUM”, поэтому при получении значения “DOCNUM”, где txtreferenceno.Text
имеет значение, равное 1. и передал его в DailyReportManager, так вот код:
public void Save(tbl_200_Dailyreport records)
{
try
{
this.db.tbl_200_Dailyreport.Add(records);
this.db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
и в получении значения txtreferenceno.Text
var max = dailyreportmanager.FindAll().Max(x => (int?)x.DOCNUM) ?? 0;
var addMax = max + 1;
txtReferenceNo.Text = Convert.ToString(addMax);
поэтому для дизайна моей базы данных
Позвольте мне опубликовать снимок экрана:
Дизайн базы данных
Когда я проверил записи, значение “DOCNUM” имеет значение, равное единице, но почему я все еще получаю эту ошибку? Пожалуйста помоги. Большое спасибо заранее.
Лучший ответ:
Чтобы указать Entity Framework, которую вы хотите вручную указать значение ключа, укажите этот атрибут:
[DatabaseGenerated(DatabaseGeneratedOption.None)]
против DOCNUM
.
У меня проблема, я только начал изучать модель EF, и я остаюсь в одной точке в течение некоторого времени. Я получил такую ошибку:
» при обновлении записей произошла ошибка. См. внутреннее исключение для деталей»
Я создал простой модели, схемы, создание базы данных и написал простой код на C#, чтобы добавить только одну строку в таблице, но ошибка появляется все время.
Я публикую скриншот с диаграммой / сгенерированной DLL / простой основной / и ошибка метания
Ссылка для большего размера: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» следующим образом (…)
(…) переопределение этого метода позволит избежать создания таблиц с множественными именами. Теперь он создаст Таблица называется «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 .
- Remove From My Forums
-
Question
-
I followed
this tutorial and wrote the following code:Module Module1 Sub Main() Dim db As New PersonModelContainer Using db db.People.Add(New Person With {.FullName = "George1"}) db.People.Add(New Person With {.FullName = "George2"}) db.People.Add(New Person With {.FullName = "George3"}) db.People.Add(New Person With {.FullName = "George4"}) db.SaveChanges() Dim per As Person Dim pipl As IQueryable(Of Person) pipl = From p In db.People Order By p.FullName Select p Console.WriteLine("All People") For Each per In pipl Console.WriteLine("- {0}", per.FullName) Next db.People.First.FullName = "Jan" db.SaveChanges() Console.WriteLine("Press any key to exit...") Console.ReadKey() End Using End Sub End Module
I then get the following error:
An error occurred while updating the entries. See the inner exception for details.
The inner exception says the following:
Default values not supported
What am I doing wrong?
Thanks for your help!
Answers
-
I’m not sure why you don’t have execute SQL , maybe it’s because you aren’t connected to the database file. Go to your database explorer and see if you can create a connection to your database file.
But long term I would recommend you install sql server management studio (SSMS), it’s very useful for connecting to a sql server or sql server CE database and being able to run queries on it and view the database objects. The VS interface for working
with databases isn’t very good.http://www.microsoft.com/download/en/details.aspx?id=7593
One thing I noticed is the auto generated code by entity framework doesn’t create an identity column on your People table. You probably want to do that. So change the create statement code that’s in your window to this:
CREATE TABLE [People] ( [Id] int identity NOT NULL, [FullName] nvarchar(4000) NOT NULL ); GO
Larcolais Gong’s database script also shows this. However Larcolais’s code is for full sql server, I don’t know if it will work with your sql ce database. I think you just need to modify your script and include the identity keyword like above.
Let me know if this works. Seems like your code is working when Larcolais and myself try it, as long as there is a valid database and identity column in the table.
Tom Overton
-
Marked as answer by
Monday, October 3, 2011 9:24 PM
-
Marked as answer by
- Remove From My Forums
-
Question
-
I followed
this tutorial and wrote the following code:Module Module1 Sub Main() Dim db As New PersonModelContainer Using db db.People.Add(New Person With {.FullName = "George1"}) db.People.Add(New Person With {.FullName = "George2"}) db.People.Add(New Person With {.FullName = "George3"}) db.People.Add(New Person With {.FullName = "George4"}) db.SaveChanges() Dim per As Person Dim pipl As IQueryable(Of Person) pipl = From p In db.People Order By p.FullName Select p Console.WriteLine("All People") For Each per In pipl Console.WriteLine("- {0}", per.FullName) Next db.People.First.FullName = "Jan" db.SaveChanges() Console.WriteLine("Press any key to exit...") Console.ReadKey() End Using End Sub End Module
I then get the following error:
An error occurred while updating the entries. See the inner exception for details.
The inner exception says the following:
Default values not supported
What am I doing wrong?
Thanks for your help!
Answers
-
I’m not sure why you don’t have execute SQL , maybe it’s because you aren’t connected to the database file. Go to your database explorer and see if you can create a connection to your database file.
But long term I would recommend you install sql server management studio (SSMS), it’s very useful for connecting to a sql server or sql server CE database and being able to run queries on it and view the database objects. The VS interface for working
with databases isn’t very good.http://www.microsoft.com/download/en/details.aspx?id=7593
One thing I noticed is the auto generated code by entity framework doesn’t create an identity column on your People table. You probably want to do that. So change the create statement code that’s in your window to this:
CREATE TABLE [People] ( [Id] int identity NOT NULL, [FullName] nvarchar(4000) NOT NULL ); GO
Larcolais Gong’s database script also shows this. However Larcolais’s code is for full sql server, I don’t know if it will work with your sql ce database. I think you just need to modify your script and include the identity keyword like above.
Let me know if this works. Seems like your code is working when Larcolais and myself try it, as long as there is a valid database and identity column in the table.
Tom Overton
-
Marked as answer by
Monday, October 3, 2011 9:24 PM
-
Marked as answer by