错误:实体类型需要主键

时间:2017-04-19 18:26:03

标签: c# wpf entity-framework-core

我想扩展这个问题上提出的问题

Binding listbox to observablecollection

赋予其持久化数据的能力。结构大致相同,只是我安装了Entity Framework Core,创建了一个DbContext类来保存记录。我添加了一个按钮将数据集保存到SQL Server。我没有遇到编译错误但是当我试图将数据保存在数据库中时,我得到了这个运行时异常:

  

消息=实体类型' Fruit'需要定义主键。

整个例外情况如下:

  

System.InvalidOperationException未处理
  的HResult = -2146233079
  消息=实体类型' 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 context,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访问者)
  在Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.get_StateManager()
  在Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges()
  在Microsoft.EntityFrameworkCore.DbContext.TryDetectChanges()
  在Microsoft.EntityFrameworkCore.DbContext.SaveChanges(布尔acceptAllChangesOnSuccess)
  在Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
  在Fruits.MainWindow.SaveFruitCommandBinding_Executed(对象发送者,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命令,布尔执行)
  在System.Windows.Input.CommandManager.OnExecuted(Object sender,ExecutedRoutedEventArgs e)              在System.Windows.UIElement.OnExecutedThunk(Object sender,ExecutedRoutedEventArgs e)              在System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler,Object target)              在System.Windows.RoutedEventArgs.InvokeHandler(委托处理程序,对象目标)              在System.Windows.RoutedEventHandlerInfo.InvokeHandler(对象目标,RoutedEventArgs routedEventArgs)              at System.Windows.EventRoute.InvokeHandlersImpl(Object source,RoutedEventArgs args,Boolean reRaised)              在System.Windows.UIElement.RaiseEventImpl(DependencyObject sender,RoutedEventArgs args)              在System.Windows.UIElement.RaiseEvent(RoutedEventArgs args,布尔值信任)              在System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter,IInputElement target,Boolean userInitiated)              在System.Windows.Input.RoutedCommand.ExecuteCore(Object parameter,IInputElement target,Boolean userInitiated)              在MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource,Boolean userInitiated)              在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(委托处理程序,对象目标)              在System.Windows.RoutedEventHandlerInfo.InvokeHandler(对象目标,RoutedEventArgs routedEventArgs)              at 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(委托处理程序,对象目标)              在System.Windows.RoutedEventHandlerInfo.InvokeHandler(对象目标,RoutedEventArgs routedEventArgs)              at 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.UIElement.RaiseEvent(RoutedEventArgs args,布尔值信任)              在System.Windows.Input.InputManager.ProcessStagingArea()              在System.Windows.Input.InputManager.ProcessInput(InputEventArgs输入)              在System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)              在System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd,InputMode模式,Int32时间戳,RawMouseActions操作,Int32 x,Int32 y,Int32轮)              在System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd,WindowMessage msg,IntPtr wParam,IntPtr lParam,Boolean&amp; processed)              在System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&amp; processed)              在MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&amp; handling)              在MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)              在System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调,对象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方法,Object args,Int32 numArgs)              在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam)              在MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg)              在System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame框架)              在System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架)              在System.Windows.Application.RunDispatcher(Object ignore)              在System.Windows.Application.RunInternal(窗口窗口)              在System.Windows.Application.Run(窗口窗口)              在System.Windows.Application.Run()              在Fruits.App.Main()              在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)              在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)              在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()              在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)              at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)              at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)              在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)              在System.Threading.ThreadHelper.ThreadStart()         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>

我的项目结构

enter image description here

我在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]

请告知为什么消息说确实存在没有主键

13 个答案:

答案 0 :(得分:65)

此异常消息并不意味着它需要在数据库中定义主键,这意味着它需要在中定义主键。

虽然你试图这样做:

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

这没有任何效果,因为实体框架忽略了只读属性。它必须:当它从数据库中检索Fruits记录时,它构造一个Fruit对象,然后为每个映射的属性调用属性setter。这对于只读属性永远不会起作用。

您需要Entity Framework才能设置ID的值。这意味着该物业需要有一个二传手。

答案 1 :(得分:14)

我带着类似的错误来到这里:

  

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!

        // ...

答案 2 :(得分:1)

我发现错误的原因有些不同。看起来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名称仍然可能,但是我们必须使用[em]属性,例如

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

答案 3 :(得分:1)

这对我有用:

using System.ComponentModel.DataAnnotations;

[Key]
public int ID { get; set; }

答案 4 :(得分:1)

如果出现错误:

<块引用>

实体类型“DeviceFlowCodes”需要一个主键 定义。如果您打算使用无键实体类型,请调用“HasNoKey” 在“OnModelCreating”中。有关无键实体类型的更多信息, 见https://go.microsoft.com/fwlink/?linkid=2141943

您可能正在使用个人用户帐户的解决方案,并在 protected override void OnModelCreating(ModelBuilder modelBuilder) 中使用了 ApplicationDbContext

错误来自带有 ApiAuthorizationDbContextpublic DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }

通过在 base.OnModelCreating(modelBuilder); 中调用 protected override void OnModelCreating 来解决错误。

来源:

https://github.com/IdentityServer/IdentityServer4/issues/3169

答案 5 :(得分:0)

  

实体类型“ 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

不确定是否有更好的解决方法,但是我将Email和PhoneNumber属性更改为字符串。问题解决了。

答案 6 :(得分:0)

您的Id属性需要有一个二传手。但是,二传手可以是私人的。 如果属性被命名为“ Id”,则[Key]属性不是必需的,因为它将通过命名约定在其中查找名称为“ Id”的键来找到它。

public Guid Id { get; }              // Will not work
public Guid Id { get; set; }         // Will work
public Guid Id { get; private set; } // Will also work

答案 7 :(得分:0)

在我从实体中删除HasNoKey()方法之前,没有一个答案有效。不要忘记从您的数据上下文中删除它,否则[Key]属性将无法解决任何问题。

答案 8 :(得分:0)

确保您具有以下条件:

  1. 如果主键名称不是[key]Id,请使用ID
  2. 使用public关键字。
  3. 主键应具有getter和setter。

示例:

public class MyEntity {
   [key]
   public Guid Id {get; set;}
}

答案 9 :(得分:0)

使用Scaffold-DbContext删除并添加回表中,错误消失

答案 10 :(得分:0)

当我使用Scaffold-DbContext命令时,它没有在模型文件中包含“ [key]”注释,也没有在“ modelBuilder.Entity”块中包含“ entity.HasKey(..)”条目。我的解决方案是在* Context.cs文件的每个“ modelBuilder.Entity”块中添加如下一行:

var petName=prompt("Enter your pet name?")
var x=petName.length-1
alert("index number of last letter is: "+x)
if(petName[x]=="y"){
   
   console.log("You have enter the right name.")    
}

我并不是说这更好,甚至是正确的方法。我只是说这对我有用。

答案 11 :(得分:0)

另一个原因可能是您的实体类具有几个名为somhow /.*id/i的属性-因此以不区分大小写的ID和基本类型结束,并且没有[Key]属性。

EF将尝试通过查找以 ID 结尾的基本类型属性来自行找出PK。

查看我的情况:

public class MyTest, IMustHaveTenant
{
  public long Id { get; set; }
  public int TenantId { get; set; }
  [MaxLength(32)]
  public virtual string Signum{ get; set; }
  public virtual string ID { get; set; }
  public virtual string ID_Other { get; set; }
}

不要问-旧代码。 Id甚至是继承的,所以我不能使用[Key](只是在这里简化代码)

但是在这里,EF完全感到困惑。

帮助的是在DBContext类中使用了modelbuilder。

            modelBuilder.Entity<MyTest>(f =>
            {
                f.HasKey(e => e.Id);
                f.HasIndex(e => new { e.TenantId });
                f.HasIndex(e => new { e.TenantId, e.ID_Other });
            });

PK上的索引是隐式的。

答案 12 :(得分:0)

我碰巧什么都试过了:

  • 确保该属性有一个 setter
  • 尝试使用 [Key] 注释
  • 具有带和不带 [Key] 注释的属性名称“Id”

没有工作的原因很简单:我的数据库不可用。

修复与数据库的连接解决了“需要主键”问题。

(奇怪的是,即使在这种情况下也会显示此错误。)