을 묻는 질문에 이 스레드
바인딩 listbox 다
에 의해 그 능력을 지속적 데이터입니다. 구조는 대개는 제외하고는 동일한 설치 엔티티 프레임워크 핵심,만든DbContext
클래스를 길게 기록합니다. 추가 버튼을 저장할 데이터 있음을 의미합니다. 가 발생하지 않은 컴파일러하지만 때 나는 저장을 시도한 데이터를 데이터베이스에서 이를 실행 시간은 예외:
Message=entity 유형'Fruit'필요한 기본 키로 정의할 수 있다. 전체적인 예외 전체에서는 아래 나열된 시스템입니다.InvalidOperationException 처리되지 않았 외=-2146233079 Message=entity 유형'Fruit'필요한 기본 키로 정의할 수 있다. Source=Microsoft.EntityFrameworkCore StackTrace: Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.ModelValidator.ShowError(문자열은 메시지) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.ModelValidator.EnsureNonNullPrimaryKeys(IModel 모델) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.ModelValidator.유효성 검사(IModel 모델) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.RelationalModelValidator.유효성 검사(IModel 모델) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext 컨텍스트,IConventionSetBuilder conventionSetBuilder,IModelValidator 검사기) 에 Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>cDisplayClass14_0.
0(체 k) 에서 시스템입니다.컬렉션이 있습니다.동시에 이루어 집니다.ConcurrentDictionary 0_6(IServiceProvider p) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteRuntimeResolver.VisitFactoryService(FactoryService factoryService,ServiceProvider 공급자) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteVisitor2.GetOrAdd(반환 키 Func
2valueFactory) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext 컨텍스트,IConventionSetBuilder conventionSetBuilder,IModelValidator 검사기) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.DbContextServices.CreateModel() Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.LazyRef`1.get_Value() Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.내부입니다.DbContextServices.get_Model() 에 Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionextensions.<>c.b 2.VisitCallSite(IServiceCallSite callSite,TArgument 인수) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProvider 공급자) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,TArgument 인수) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite,ServiceProvider 공급자) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite callSite,TArgument 인수) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProvider 공급자) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,TArgument 인수) 에 Microsoft.Extensions.DependencyInjection.ServiceProvider.<>cDisplayClass16_0.b__0(ServiceProvider 공급자) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceProvider.GetService(Type serviceType) Microsoft 에서 사용할 수 있습니다.Extensions.제 모든 시스템.ServiceProviderServiceExtensions.GetService[T](IServiceProvider 공급자) 에 Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetServiceTService Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.ChangeTracking.ChangeTracker.get_StateManager() Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges() Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.DbContext.TryDetectChanges() Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.DbContext.문제를 재현(Boolean acceptAllChangesOnSuccess) Microsoft 에서 사용할 수 있습니다.EntityFrameworkCore.DbContext.문제를 재현() 에서 과일.MainWindow.SaveFruitCommandBinding_Executed(객체를 보낸 사람,ExecutedRoutedEventArgs e)D:\Frank\Test\Fruits\Fruits\MainWindow.xaml.cs:line 50 에서 시스템입니다.Windows.입력합니다.CommandBinding.OnExecuted(객체를 보낸 사람,ExecutedRoutedEventArgs e) 에서 시스템입니다.Windows.입력합니다.CommandManager.ExecuteCommandBinding(객체를 보낸 사람,ExecutedRoutedEventArgs e,CommandBinding commandBinding) 에서 시스템입니다.Windows.입력합니다.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings,객체를 보낸 사람,RoutedEventArgs e,ICommand 명령,부울 실행) 에서 시스템입니다.Windows.입력합니다.CommandManager.FindCommandBinding(객체를 보낸 사람,RoutedEventArgs e,ICommand 명령,부울 실행) 에서 시스템입니다.Windows.입력합니다.CommandManager.OnExecuted(객체를 보낸 사람,ExecutedRoutedEventArgs e) 에서 시스템입니다.Windows.UIElement.OnExecutedThunk(객체를 보낸 사람,ExecutedRoutedEventArgs e) 에서 시스템입니다.Windows.입력합니다.ExecutedRoutedEventArgs.InvokeEventHandler(대리인 genericHandler,객체를 대상) 에서 시스템입니다.Windows.RoutedEventArgs.InvokeHandler(대리인 핸들러,객체를 대상) 에서 시스템입니다.Windows.RoutedEventHandlerInfo.InvokeHandler(객체를 대상,RoutedEventArgs routedEventArgs) 에서 시스템입니다.Windows.EventRoute.InvokeHandlersImpl(Object 원,RoutedEventArgs args,Boolean reRaised) 에서 시스템입니다.Windows.UIElement.RaiseEventImpl(인 경우 보낸 사람,RoutedEventArgs args) 에서 시스템입니다.Windows.UIElement.이(RoutedEventArgs args,신뢰할 수 있는 부울) 에서 시스템입니다.Windows.입력합니다.RoutedCommand.ExecuteImpl(개체 매개변수,IInputElement 대상,Boolean userInitiated) 에서 시스템입니다.Windows.입력합니다.RoutedCommand.ExecuteCore(개체 매개변수,IInputElement 대상,Boolean userInitiated) 에서 양 내부입니다.명령입니다.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource,Boolean userInitiated) 에서 시스템입니다.Windows.컨트롤이 있습니다.프리미티브입니다.ButtonBase.OnClick() 에서 시스템입니다.Windows.컨트롤이 있습니다.단추입니다.OnClick() 에서 시스템입니다.Windows.컨트롤이 있습니다.프리미티브입니다.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) 에서 시스템입니다.Windows.UIElement.OnMouseLeftButtonUpThunk(객체를 보낸 사람,MouseButtonEventArgs e) 에서 시스템입니다.Windows.입력합니다.MouseButtonEventArgs.InvokeEventHandler(대리인 genericHandler,체 genericTarget) 에서 시스템입니다.Windows.RoutedEventArgs.InvokeHandler(대리인 핸들러,객체를 대상) 에서 시스템입니다.Windows.RoutedEventHandlerInfo.InvokeHandler(객체를 대상,RoutedEventArgs routedEventArgs) 에서 시스템입니다.Windows.EventRoute.InvokeHandlersImpl(Object 원,RoutedEventArgs args,Boolean reRaised) 에서 시스템입니다.Windows.UIElement.ReRaiseEventAs(인 경우 보낸 사람,RoutedEventArgs args,RoutedEvent newEvent) 에서 시스템입니다.Windows.UIElement.OnMouseUpThunk(객체를 보낸 사람,MouseButtonEventArgs e) 에서 시스템입니다.Windows.입력합니다.MouseButtonEventArgs.InvokeEventHandler(대리인 genericHandler,체 genericTarget) 에서 시스템입니다.Windows.RoutedEventArgs.InvokeHandler(대리인 핸들러,객체를 대상) 에서 시스템입니다.Windows.RoutedEventHandlerInfo.InvokeHandler(객체를 대상,RoutedEventArgs routedEventArgs) 에서 시스템입니다.Windows.EventRoute.InvokeHandlersImpl(Object 원,RoutedEventArgs args,Boolean reRaised) 에서 시스템입니다.Windows.UIElement.RaiseEventImpl(인 경우 보낸 사람,RoutedEventArgs args) 에서 시스템입니다.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) 에서 시스템입니다.Windows.UIElement.이(RoutedEventArgs args,신뢰할 수 있는 부울) 에서 시스템입니다.Windows.입력합니다.InputManager.ProcessStagingArea() 에서 시스템입니다.Windows.입력합니다.InputManager.ProcessInput(InputEventArgs 입력) 에서 시스템입니다.Windows.입력합니다.InputProviderSite.ReportInput(InputReport inputReport) 에서 시스템입니다.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd,InputMode 모드 Int32 타임스탬프,RawMouseActions 작업,Int32x,Int32y,Int32 휠) 에서 시스템입니다.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd,WindowMessage msg,IntPtr wParam,IntPtr lParam,Boolean&처리) 에서 시스템입니다.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,Int32msg,IntPtr wParam,IntPtr lParam,Boolean&처리) 에서 양 Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32msg,IntPtr wParam,IntPtr lParam,Boolean&처리) 에서 양 Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 에서 시스템입니다.Windows.Threading.ExceptionWrapper.InternalRealCall(대리인 콜백체 args,Int32numArgs) 에서 시스템입니다.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object 원,대리인,콜백체 args,Int32numArgs,대리인 catchHandler) 에서 시스템입니다.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority 우선순위,기간을 제한시간,위임하는 방법,물체 인수,Int32numArgs) 에서 양 Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32msg,IntPtr wParam,IntPtr lParam) 에서 양 Win32.UnsafeNativeMethods.DispatchMessage(MSG&msg) 에서 시스템입니다.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame 프레임) 에서 시스템입니다.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame 프레임) 에서 시스템입니다.Windows.응용 프로그램.RunDispatcher(객체를 무시) 에서 시스템입니다.Windows.응용 프로그램.RunInternal(윈도우 창) 에서 시스템입니다.Windows.응용 프로그램.실행(Window 창) 에서 시스템입니다.Windows.응용 프로그램.Run() 에서 과일.App.Main() 에서 시스템입니다.사용되지 않._nExecuteAssembly(RuntimeAssembly 어셈블리,String[]args) 에서 시스템입니다.사용되지 않.ExecuteAssembly(문자열을 경우,증거 assemblySecurity,String[]args) Microsoft 에서 사용할 수 있습니다.Visual studio.HostingProcess.HostProc.RunUsersAssembly() 에서 시스템입니다.Threading.ThreadHelper.ThreadStart_Context(체 상태) 에서 시스템입니다.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback 콜백체 상태,Boolean preserveSyncCtx) 에서 시스템입니다.Threading.ExecutionContext.실행(ExecutionContext executionContext,ContextCallback 콜백체 상태,Boolean preserveSyncCtx) 에서 시스템입니다.Threading.ExecutionContext.실행(ExecutionContext executionContext,ContextCallback 콜백체 상태) 에서 시스템입니다.Threading.ThreadHelper.ThreadStart() InnerException: 이 업데이트 클래스 과일:
namespace Fruits.ViewModels
{
[Table("Fruits")]
public class Fruit : ViewModelBase
{
#region Constractor
public Fruit()
{
}
public Fruit(string name, String clrString)
{
FruitName = name;
// Parse colors like so: (Color)ColorConverter.ConvertFromString(clrString);
FruitColor = clrString;
_id = Guid.NewGuid();
}
public Fruit(string name, Color clr)
{
FruitName = name;
FruitColor = clr.ToString();
_id = Guid.NewGuid();
}
#endregion
#region Properties
private Guid _id;
[Key]
public Guid ID
{
get { return _id; }
}
#region FruitName
private string _fruitname;
public string FruitName
{
get
{
return _fruitname;
}
set
{
if (_fruitname != value)
{
_fruitname = value;
OnPropertyChanged("FruitName");
}
}
}
#endregion
#region FruitColor
private String _fruitcolor;
public String FruitColor
{
get
{
return _fruitcolor;
}
set
{
if (_fruitcolor != value)
{
_fruitcolor = value;
OnPropertyChanged("FruitColor");
}
}
}
#endregion
#region Selected Property
private bool _isSelected = true;
// NOTE: I renamed this property
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected != value)
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
#endregion
#endregion
}
}
업데이트 MainWindows xaml(추가 저장 버튼)
<Window x:Class="Fruits.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Fruits"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<RoutedCommand x:Key="AddFruit" />
<RoutedCommand x:Key='SaveFruit' />
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command='{StaticResource AddFruit}'
Executed='AddFruitCommandBinding_Executed'
CanExecute='AddFruitCommandBinding_CanExecute' />
<CommandBinding Command='{StaticResource SaveFruit}'
Executed='SaveFruitCommandBinding_Executed'
CanExecute='SaveFruitCommandBinding_CanExecute' />
</Window.CommandBindings>
<Grid>
<StackPanel Orientation='Vertical'
Margin='10'>
<CheckBox IsChecked="{Binding ShowSelectedFruitOnly}">Selected Fruit Only</CheckBox>
<ListBox x:Name='MyList'
ItemsSource="{Binding FruitsView}"
ItemTemplate='{StaticResource FruitTemp}' />
<StackPanel Orientation="Horizontal"
Margin="0,10,0,0">
<Label Width="100">New Name:</Label>
<TextBox Width="200"
Text="{Binding NewFruitName, Mode=TwoWay }"
/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="0,10,0,0">
<Label Width="100">New Color:</Label>
<!--<TextBox Width="200"
Text="{Binding NewFruitColor, UpdateSourceTrigger=PropertyChanged}" />-->
<TextBox Width="200"
Text="{Binding NewFruitColor, Mode=TwoWay }" />
<ContentControl Style="{StaticResource ColorSwatch}"
Margin="2"
VerticalAlignment="Center"
Content="{Binding NewFruitColor}" />
</StackPanel>
<StackPanel Orientation='Horizontal'>
<Button x:Name='AddFruit'
Height='auto'
Width='auto'
Content='Add New Fruit 2'
Margin='0,10,0,0'
Command='{StaticResource AddFruit}' />
<Button x:Name='SaveFruit'
Height='auto'
Width='auto'
Content='Save Fruit'
Margin='100,10,0,0'
Command='{StaticResource SaveFruit}' />
</StackPanel>
</StackPanel>
</Grid>
</Window>
와 내 뒤에 코드 mainwindows(추가 처리기)
using Fruits.ViewModels;
using System;
using System.Windows;
using System.Windows.Input;
namespace Fruits
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
ViewModel.AddNewFruit("Jackfruit", "Yellow");
ViewModel.AddNewFruit("Watermelon", "ForestGreen");
ViewModel.AddNewFruit("Apple", "Red");
ViewModel.AddNewFruit("Banana", "Yellow");
ViewModel.AddNewFruit("Orange", "DeepSkyBlue");
//ViewModel.Fruits[0].IsSelected = false;
//ViewModel.Fruits[1].IsSelected = false;
ViewModel.FruitsView.Refresh();
}
public MainViewModel ViewModel { get { return DataContext as MainViewModel; } }
private void AddFruitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
ViewModel.AddNewFruit();
}
private void AddFruitCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute =
ViewModel != null
&& !String.IsNullOrWhiteSpace(ViewModel.NewFruitName)
&& !String.IsNullOrWhiteSpace(ViewModel.NewFruitColor)
;
}
private void SaveFruitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
using (var db=new FruitDbContext())
{
db.SaveChanges();
}
}
private void SaveFruitCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
}
}
내가 새롭게 추가 dbContext:
namespace Fruits.ViewModels
{
public class FruitDbContext:DbContext
{
public DbSet<Fruit> Fruits { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
{
optionBuilder.UseSqlServer(@"Server = xxx; Database=Test; Integrated Security = True");
}
}
}
다른 클래스에는 변경되지 않지만,나열된 어쨌든 그들: ViewModelBase
namespace Fruits.ViewModels
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
ViewModel
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Media;
namespace Fruits.ViewModels
{
#region MainViewModel Class
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
Fruits = new ObservableCollection<Fruit>();
}
public ICollectionView FruitsView { get; private set; }
#region ShowSelectedFruitOnly Property
private bool _showSelectedFruitOnly = true;
public bool ShowSelectedFruitOnly
{
get { return _showSelectedFruitOnly; }
set
{
if (value != _showSelectedFruitOnly)
{
_showSelectedFruitOnly = value;
FruitsView.Refresh();
OnPropertyChanged("ShowSelectedFruitOnly");
}
}
}
#endregion ShowSelectedFruitOnly Property
#region Add Methods
public void AddNewFruit()
{
Fruits.Add(new Fruit(NewFruitName, NewFruitColor));
NewFruitName = "";
NewFruitColor = "";
}
public void AddNewFruit(string name, string color)
{
Fruits.Add(new Fruit(name, color));
}
public void AddNewFruit(string name, Color color)
{
Fruits.Add(new Fruit(name, color));
}
#endregion Add Methods
#region NewFruitName Property
private String _newFruitName = default(String);
public String NewFruitName
{
get { return _newFruitName; }
set
{
if (value != _newFruitName)
{
_newFruitName = value;
OnPropertyChanged("NewFruitName");
}
}
}
#endregion NewFruitName Property
#region NewFruitColor Property
private String _newFruitColor = default(String);
public String NewFruitColor
{
get { return _newFruitColor; }
set
{
if (value != _newFruitColor)
{
_newFruitColor = value;
OnPropertyChanged("NewFruitColor");
}
}
}
#endregion NewFruitColor Property
#region Fruits Property
private static ObservableCollection<Fruit> _fruits;
public ObservableCollection<Fruit> Fruits
{
get { return _fruits; }
private set
{
if (value != _fruits)
{
_fruits = value;
FruitsView = CollectionViewSource.GetDefaultView(Fruits);
FruitsView.Filter = FruitFilterPredicate;
FruitsView.Refresh();
OnPropertyChanged("Fruits");
}
}
}
protected bool FruitFilterPredicate(Object o)
{
if (ShowSelectedFruitOnly)
{
return (o as Fruit).IsSelected;
}
return true;
}
#endregion Fruits Property
}
#endregion MainViewModel Class
}
App.xaml
<Application x:Class="Fruits.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Fruits"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="ColorSwatch"
TargetType="ContentControl">
<Setter Property="Width"
Value="24" />
<Setter Property="Height"
Value="24" />
<Setter Property="IsTabStop"
Value="false" />
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Rectangle HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Stroke="Gray"
StrokeThickness="1">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding}" />
</Rectangle.Fill>
</Rectangle>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key='FruitTemp'>
<StackPanel Orientation='Horizontal'
Margin='5'>
<TextBlock x:Name='tbName'
Text='{Binding FruitName}'
Margin='10,0,0,0'
Width='100' />
<TextBlock x:Name='tbColor'
Text='{Binding FruitColor}'
Margin='10,0,0,0'
Width='100' />
<ContentControl Width="16"
Height="16"
Style="{StaticResource ColorSwatch}"
Content="{Binding FruitColor}" />
<!-- The problem here was you were trying to bind Checked, an event,
instead if IsChecked, a bool? property.
-->
<CheckBox x:Name='cbSelected'
Content='Selected'
Margin='10,0,0,0'
IsChecked='{Binding IsSelected}' />
</StackPanel>
</DataTemplate>
</Application.Resources>
</Application>
의 구조 내 프로젝트 내 테이블에서 SQL Server:
CREATE TABLE [dbo].[Fruits]
(
[ID] [uniqueidentifier] NOT NULL,
[FruitName] [nvarchar](50) NULL,
[FruitColor] [nvarchar](50) NULL,
[IsSelected] [nvarchar](1) NULL,
CONSTRAINT [PK_Fruit]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
조언하십시오 왜 메시지가 없다고 말했 기본 키가 있는 동안 그것이 존재하지 않습니다
이 예외 메시지지 않는't 평균이 필요할 수 있도록 기본 키에서 정의하데이터베이스,그 의미가 필요할 수 있도록 기본 키에서 정의클래스.
비록 당신이've 도 그렇게 하려면 다음과 같이 합니다.
개인 Guid 그리고 우; [Key] 공 Guid ID { 얻을{return 그리고 우;} }
이 효과가 없으로,엔티티 프레임 워크를 무시 읽기 전용 속성이 있습니다. 그것은 있을 때는 그것을 검색과
녹화 데이터베이스에서,그것은 구성과
개체화의 속성을 세팅에 대한 각 매핑을 제공합니다. 는's 결코 작동하는 것에 대한 읽기 전용 속성이 있습니다.
당신이 필요로 엔티티 프레임워크를 설정할 수 있는 값의ID
. 이 뜻의 속성이 있어야 setter.
여기에 왔는 유사한 오류:
시스템입니다.InvalidOperationException:'entity 유형'클래스 라이브러리 또'필요한 기본 키로 정의할 수 있다.'
후 읽기에 대답하여 hvd,는 것을 깨달았을 잊을 키 속'공'. 니다.
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
int Id { get; set; }
// ...
해야 합니다.
namespace MyApp.Models.Schedule
{
public class MyType
{
[Key]
public int Id { get; set; } // must be public!
// ...
귀하의 Id 속성을 요구하였습니다. 그러나 세터 수 있습니다.
을[Key]
특성이 필요하지 않는 경우 호텔 이름"Id"그대로 그것을 찾을 수 있을 통해 이름 지정 규칙에 보이는 곳에 대한 열쇠와 이름"Id".
public Guid Id { get; } // Will not work
public Guid Id { get; set; } // Will work
public Guid Id { get; private set; } // Will also work
내가 찾는 조금 다른 원인 오류가 있습니다. 는 것 같 SQLite 을 사용하려는 정확한 주요 키 클래스의 속성 이름입니다. 그래서...
잘못된 PK 이름
public class Client
{
public int SomeFieldName { get; set; } // It is the ID
...
}
올바른 PK 이름
public class Client
{
public int Id { get; set; } // It is the ID
...
}
public class Client
{
public int ClientId { get; set; } // It is the ID
...
}
그것은 아직도 가망을 사용하여 잘못된 PK 이름이지만 우리가 사용하는[특성을 좋아
public class Client
{
[Key]
public int SomeFieldName { get; set; } // It is the ID
...
}
entity 유형'DisplayFormatAttribute'이 필요할 수 있도록 기본 키 정의됩니다.
내 경우에는 제가 생각한 문제는 내가 사용하는 속성을 다음과 같이:
public string LastName { get; set; } //OK
public string Address { get; set; } //OK
public string State { get; set; } //OK
public int? Zip { get; set; } //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; } // NOT OK
지 확신이 있을 경우는 더 나은 방법으로 해결하는 그러나 나는 이메일과 PhoneNumber 특성하는 문자열을 사용합니다. 문제를 해결합니다.