錯誤:實體類型需要主鍵

c# entity-framework-core wpf

我想擴展這個問題上提出的問題

將列錶框綁定到observablecollection

通過賦予它持久化數據的能力。除了我安裝Entity Framework Core之外,結構大致相同,創建了一個DbContext類來保存記錄。我添加了一個按鈕將數據集保存到SQL Server。我沒有遇到編譯錯誤但是當我試圖將數據保存在數據庫中時,我得到了這個運行時異常:

Message =實體類型'Fruit'需要定義主鍵。

整個例外情況如下

System.InvalidOperationException未處理
的HResult = -2146233079
Message =實體類型'Fruit'需要定義主鍵。
來源= Microsoft.EntityFrameworkCore
堆棧跟踪:
在Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)
在Microsoft.EntityFrameworkCore.Internal.ModelValidator.EnsureNonNullPrimaryKeys(IModel模型)
在Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel模型)
在Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel模型)
在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext上下文,IConventionSetBuilder conventionSetBuilder,IModelValidator驗證器)
在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource。<> c__DisplayClass14_0.b__0(對象k)
在System.Collections.Concurrent.ConcurrentDictionary 2.GetOrAdd(TKey key, Func 2 valueFactory)
在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext上下文,IConventionSetBuilder conventionSetBuilder,IModelValidator驗證器)
在Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
在Microsoft.EntityFrameworkCore.Internal.LazyRef 1.get_Value()
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_6(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactoryService(FactoryService factoryService, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,TArgument參數)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProvider provider)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,TArgument參數)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProvider provider)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure
1 accessor)
在Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.get_StateManager()
在Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()
在Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()
在Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
在Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
在Fruits:MainWindow.SaveFruitCommandBinding_Executed(Object sender,ExecutedRoutedEventArgs e)在D:\ Frank \ Test \ Fruits \ Fruits \ MainWindow.xaml.cs:第50行
在System.Windows.Input.CommandBinding.OnExecuted(Object sender,ExecutedRoutedEventArgs e)
在System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender,ExecutedRoutedEventArgs e,CommandBinding commandBinding)
在System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings,Object sender,RoutedEventArgs e,ICommand command,Boolean execute)
在System.Windows.Input.CommandManager.FindCommandBinding(對象發送者,RoutedEventArgs e,ICommand命令,布爾執行)
at System.Windows.Input.CommandManager.OnExecuted(Object sender,ExecutedRoutedEventArgs e)at System.Windows.UIElement.OnExecutedThunk(Object sender,ExecutedRoutedEventArgs e)at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler,Object target)at at系統中System.Windows.EventRoute.InvokeHandlersImpl(Object source,RoutedEventArgs args,Boolean reRaised)的System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,RoutedEventArgs routedEventArgs)中的System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler,Object target)。 System.Windows.UIElement.RaiseEvent(RoutedEventArgs args,布爾值受信任)的System.Windows.Input.RoutedCommand.ExecuteImpl(Object參數,IInputElement target,Boolean userInitiated)中的Windows.UIElement.RaiseEventImpl(DependencyObject sender,RoutedEventArgs args)。 MS.Internal.Commands.CommandHel中的Windows.Input.RoutedCommand.ExecuteCore(Object parameter,IInputElement target,Boolean userInitiated) System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs)中的System.Windows.Controls.Button.OnClick()處的System.Windows.Controls.Primitives.ButtonBase.OnClick()中的pers.CriticalExecuteCommandSource(ICommandSource commandSource,Boolean userInitiated) e)位於System.Windows.RindtedEventArgs.InvokeHandler(委託處理程序,對象目標)的System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler,Object genericTarget)中的System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender,MouseButtonEventArgs e)at at在System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender,RoutedEventArgs args,RoutedEvent newEvent)的System.Windows.EventRoute.InvokeHandlersImpl(Object source,RoutedEventArgs args,Boolean reRaised)中的System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,RoutedEventArgs routedEventArgs) System.Windows.Input.MouseButt上的System.Windows.UIElement.OnMouseUpThunk(Object sender,MouseButtonEventArgs e) System.Windows.EventRoute.InvokeHandlersImpl(Object)上的System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,RoutedEventArgs routedEventArgs)上的System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler,Object target)中的onEventArgs.InvokeEventHandler(Delegate genericHandler,Object genericTarget)在System.Windows.Uindlement.RaiseEvent(RoutedEventArgs args,布爾值受信任)的System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)的System.Windows.UIElement.RaiseEventImpl(DependencyObject sender,RoutedEventArgs args)中的source,RoutedEventArgs args,Boolean reRaised)處於System.Windows.Inputop.HwndMouseInputProvider.ReportInput中System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)的System.Windows.Input.InputManager.ProcessInput(InputEventArgs輸入)中的System.Windows.Input.InputManager.ProcessStagingArea() System.Windows.Interop.H上的(IntPtr hwnd,InputMode模式,Int32時間戳,RawMouseActions操作,Int32 x,Int32 y,Int32輪)在MS.Win32的System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&handling)中的wndMouseInputProvider.FilterMessage(IntPtr hwnd,WindowMessage msg,IntPtr wParam,IntPtr lParam,Boolean&handling)。在System.Windows.Threading.ExceptionWrapper.InternalRealCall的MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)中的HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&handling)(委託回調,Object args,Int32 numArgs )在System.Windows.Threading.Dispatcher.LegacyInvokeImpl的System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,Delegate callback,Object args,Int32 numArgs,Delegate catchHandler)中(DispatcherPriority優先級,TimeSpan超時,Delegate方法,Object args,位於System.Windows.Threading.Dispatch的MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&msg)的MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam)上的Int32 numArgs) System.Windows上的System.Windows.Application.RunInternal(窗口窗口)中的System.Windows.Application.RunDispatcher(Object ignore)處的System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架)中的er.PushFrameImpl(DispatcherFrame框架)。 System.AppDomain.ExecuteAssembly(String assemblyFile,證據assemblySecurity,String [] args)位於System.Threading.Thread上的Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()處於System.Threading.TereadStart_Context(Object狀態),執行文件執行上下文(ExecutionContext executionContext,ContextCallback回調,對象狀態, System.Threading.ExecutionContext.Run上的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回調,Object狀態,Boolean preserveSyncCtx)中的Boolean preserveSyncCtx(ExecutionContext exec) System.Threading.ThreadHelper.ThreadStart()中的utionContext,ContextCallback回調,對象狀態InnerException:

這是更新的類Fruit:

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]

請告知為什麼消息說它確實存在時沒有主鍵

一般承認的答案

此異常消息並不意味著它需要在數據庫中定義主鍵,這意味著它需要在您的類中定義主鍵。

雖然你試圖這樣做:

private Guid _id;
[Key]
public Guid ID
{
    get { return _id; }
}

這沒有任何效果,因為實體框架忽略只讀屬性。它必須:當它從數據庫中檢索Fruits記錄時,它構造一個Fruit對象,然後為每個映射的屬性調用屬性setter。這對於只讀屬性永遠不會起作用。

您需要Entity Framework才能設置ID的值。這意味著該物業需要一個二傳手。


熱門答案

我帶著類似的錯誤來到這裡:

System.InvalidOperationException:'實體類型'MyType'需要定義主鍵。

在讀完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!

        // ...


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow