我是初学者,我正在编写一个ASP.NET MVC4项目。首先,我创建了一个数据库,然后将它连接到项目,编写了类,现在我遇到了一些问题。问题是由于"Invalid column name 'Song_SongID'".
课程看起来如此:
[Table("Users")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public System.DateTime DateOfBirth { get; set; }
public string Email { get; set; }
public string AboutYourself { get; set; }
public string Guitar { get; set; }
public string Country { get; set; }
public string ProfilePic { get; set; }
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Song> UserLikes { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
[Table("Songs")]
public class Song
{
public int SongID { get; set; }
public string Name { get; set; }
public string Genre { get; set; }
public string File { get; set; }
public System.DateTime DateOfPost { get; set; }
public string Lyrics { get; set; }
public short Likes { get; set; }
public int UserUserID { get; set; }
public virtual User User { get; set; }
public virtual ICollection<User> UsersWhoLiked { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
[Table("Comments")]
public class Comment
{
public int CommentID { get; set; }
public int UserUserID { get; set; }
public int SongSongID { get; set; }
public virtual Song Song { get; set; }
public virtual User User { get; set; }
}
数据库包含与上述相同的表和列,但另一个表包含2个外键:UsersWhoLiked_UserID
和UserLikes_SongID
,但这在我的问题中并不重要。
我尝试了在网上找到的所有内容。我重命名了属性和列,将属性写入属性并且没有任何效果。如果您有任何想法,请帮助我。谢谢!
如所述,stacktrace:
[SqlException (0x80131904): Invalid column name 'Song_SongID'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753346
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295154
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1325
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +437
[EntityCommandExecutionException: При выполнении определения команды произошла ошибка. Подробные сведения см. во внутреннем исключении.]
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +507
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +730
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +131
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +36
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +179
System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2(IEnumerable`1 sequence) +41
System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +59
System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +133
System.Linq.Queryable.SingleOrDefault(IQueryable`1 source) +251
System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName) +889
System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues) +192
System.Data.Entity.DbSet`1.Find(Object[] keyValues) +47
AcousticMinuteMVC.Controllers.HomeController.Account() in c:\Users\Alex\Documents\Visual Studio 2012\Projects\AcousticMinuteMVC\AcousticMinuteMVC\Controllers\HomeController.cs:34
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
答案 0 :(得分:1)
此代码:
using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Data.Objects.SqlClient;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace testef {
[Table("Users")]
public class User {
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public System.DateTime DateOfBirth { get; set; }
public string Email { get; set; }
public string AboutYourself { get; set; }
public string Guitar { get; set; }
public string Country { get; set; }
public string ProfilePic { get; set; }
public virtual ICollection<Song> Songs { get; set; }
public virtual ICollection<Song> UserLikes { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
[Table("Songs")]
public class Song {
public int SongID { get; set; }
public string Name { get; set; }
public string Genre { get; set; }
public string File { get; set; }
public System.DateTime DateOfPost { get; set; }
public string Lyrics { get; set; }
public short Likes { get; set; }
public int UserUserID { get; set; }
public virtual User User { get; set; }
public virtual ICollection<User> UsersWhoLiked { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
[Table("Comments")]
public class Comment {
public int CommentID { get; set; }
public int UserUserID { get; set; }
public int SongSongID { get; set; }
public virtual Song Song { get; set; }
public virtual User User { get; set; }
}
public class TestEFContext : DbContext {
public DbSet<User> Users { get; set; }
public DbSet<Song> Songs { get; set; }
public DbSet<Comment> Comments { get; set; }
public TestEFContext(String cs)
: base(cs) {
Database.SetInitializer<TestEFContext>(new DropCreateDatabaseAlways<TestEFContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Comment>().HasRequired(x => x.Song).WithMany(y => y.Comments).WillCascadeOnDelete(false);
modelBuilder.Entity<Comment>().HasRequired(x => x.User).WithMany(y => y.Comments).WillCascadeOnDelete(false);
}
}
class Program {
static void Main(string[] args) {
String cs = @"Data Source=ALIASTVALK;Initial Catalog=TestEF;Integrated Security=True; MultipleActiveResultSets=True";
using (TestEFContext ctx = new TestEFContext(cs)) {
Console.WriteLine("The value is " + ctx.Users.Count().ToString());
}
}
}
}
生成下表:
USE [TestEF]
GO
/****** Object: Table [dbo].[Users] Script Date: 03/12/2013 15:07:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](max) NULL,
[LastName] [nvarchar](max) NULL,
[DateOfBirth] [datetime] NOT NULL,
[Email] [nvarchar](max) NULL,
[AboutYourself] [nvarchar](max) NULL,
[Guitar] [nvarchar](max) NULL,
[Country] [nvarchar](max) NULL,
[ProfilePic] [nvarchar](max) NULL,
[Song_SongID] [int] NULL,
CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH CHECK ADD CONSTRAINT [FK_dbo.Users_dbo.Songs_Song_SongID] FOREIGN KEY([Song_SongID])
REFERENCES [dbo].[Songs] ([SongID])
GO
ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_dbo.Users_dbo.Songs_Song_SongID]
GO
与FK说道。