PDA

View Full Version : ساخت database با Code first



مهیار.
سه شنبه 05 مرداد 1395, 19:07 عصر
سلام دوستان من میخواستم یک دیتا بیس از طریق Code first ایجاد کنم ..
اما نمیدونم مشکلم کجاست ؟؟! و چرا به اروو میخوردم ؟؟ من کانکشن استیرنگ هم ب صورت زیر تعریف کردم .. دوستان میتونن راهنمایی کنن؟؟
ویا یک نمونه میخواستم دیتا بیس از طریق Code first برام بزارین ..


add name="SchoolContext" connectionString="Data Source=.;Initial Catalog=SchoolContext;Integrated Security=True" providerName="System.Data.SqlClient"



static void Main(string[] args)
{
var ctx = new SchoolContext();


Student stud = new Student() { StudentName = "New Student" };


ctx.Students.Add(stud);
ctx.SaveChanges();


}


public class SchoolContext : DbContext
{
public SchoolContext(): base()
{


}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}


public class Student
{
public Student()
{


}
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }


public Teacher Teacher { get; set; }


public Standard Standard { get; set; }
}


public class Standard
{
public Standard()
{


}
public int StandardId { get; set; }
public string StandardName { get; set; }


public ICollection<Student> Students { get; set; }


}
public class Teacher
{
public Teacher()
{


}
public int TeacherId { get; set; }
public string TeacherName { get; set; }
}



141680

ژیار رحیمی
سه شنبه 05 مرداد 1395, 21:29 عصر
شما نام کانکشن استرینگ رو بعنوان پارامتر ورودی base مقدار دهی کن

public SchoolContext(): base("SchoolContext"){}

مهیار.
چهارشنبه 06 مرداد 1395, 22:34 عصر
شما نام کانکشن استرینگ رو بعنوان پارامتر ورودی base مقدار دهی کن

بازم ارور میده :

141699



مشکل از کانکشن استرینگ تو Appconfig نیست ؟؟!


<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrame workSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<configuration>
</configuration>
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=.;Initial Catalog=SchoolContext;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectio nFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>



متن اروشم اینه :


System.TypeInitializationException was unhandled HResult=-2146233036
Message=The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
Source=EntityFramework
TypeName=System.Data.Entity.Internal.AppConfig
StackTrace:
at System.Data.Entity.Internal.LazyInternalConnection ..ctor(DbContext context, String nameOrConnectionString)
at System.Data.Entity.DbContext..ctor(String nameOrConnectionString)
at CodeFirst_01.Program.SchoolContext..ctor() in D:\New Project\CodeFirst_01\CodeFirst_01\Program.cs:line 25
at CodeFirst_01.Program.Main(String[] args) in D:\New Project\CodeFirst_01\CodeFirst_01\Program.cs:line 14
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object state)
at System.Threading.ExecutionContext.RunInternal(Exec utionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
BareMessage=Configuration system failed to initialize
HResult=-2146232062
Line=0
Message=Configuration system failed to initialize
Source=System.Configuration
StackTrace:
at System.Configuration.ConfigurationManager.PrepareC onfigSystem()
at System.Configuration.ConfigurationManager.GetSecti on(String sectionName)
at System.Configuration.PrivilegedConfigurationManage r.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.Initia lize()
at System.Diagnostics.DiagnosticsConfiguration.get_In dentSize()
at System.Diagnostics.TraceInternal.InitializeSetting s()
at System.Diagnostics.TraceInternal.get_Listeners()
InnerException:
BareMessage=Unrecognized configuration section configuration.
Filename=D:\New Project\CodeFirst_01\CodeFirst_01\bin\Debug\CodeFi rst_01.vshost.exe.Config
HResult=-2146232062
Line=7
Message=Unrecognized configuration section configuration. (D:\New Project\CodeFirst_01\CodeFirst_01\bin\Debug\CodeFi rst_01.vshost.exe.Config line 7)
Source=System.Configuration
StackTrace:
at System.Configuration.ConfigurationSchemaErrors.Thr owIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.Throw IfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.Throw IfInitErrors()
at System.Configuration.ClientConfigurationSystem.Ens ureInit(String configKey)
InnerException:

omid nasri
چهارشنبه 06 مرداد 1395, 22:56 عصر
جواب سوال شما در لینک زیر قابل دسترس است:

http://stackoverflow.com/questions/17585611/the-type-initializer-for-system-data-entity-internal-appconfig-threw-an-except
و اینجا:

https://www.google.com/search?q=the+type+initializer+for+%27system.data.e ntity.internal.appconfig%27+threw+an+exception&ie=utf-8&oe=utf-8
سوال بود در خدمتیم.

ژیار رحیمی
چهارشنبه 06 مرداد 1395, 23:08 عصر
اگر به پیام خطا توجه کرده باشی
Message=Unrecognized configuration section configuration. (D:\New Project\CodeFirst_01\CodeFirst_01\bin\Debug\CodeFi rst_01.vshost.exe.Config line 7)
در خط هفتم از فایل کانفیگ شما یک tag اضافه <configuration> گذاشتی اونو بردار

مهیار.
چهارشنبه 06 مرداد 1395, 23:12 عصر
جواب سوال شما در لینک زیر قابل دسترس است:

و اینجا:

سوال بود در خدمتیم.

من چیزی نفهمیدم!

مهیار.
چهارشنبه 06 مرداد 1395, 23:20 عصر
اگر به پیام خطا توجه کرده باشی
Message=Unrecognized configuration section configuration. (D:\New Project\CodeFirst_01\CodeFirst_01\bin\Debug\CodeFi rst_01.vshost.exe.Config line 7)
در خط هفتم از فایل کانفیگ شما یک tag اضافه <configuration> گذاشتی اونو بردار
خییییییییییلی ممنون درست شد :) :تشویق::تشویق: .. پایگاه داده رو درست شد ..
فقط یچیز دیگه موقع درج این اروو هنوز هست ..

141701

static void Main(string[] args) {
var ctx = new SchoolContext();

Student stud = new Student() { StudentName = "New Student" };


ctx.Students.Add(stud);
ctx.SaveChanges();

}


ارورش اینه :

System.Data.Entity.Infrastructure.DbUpdateExceptio n was unhandled HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveCh anges()
at System.Data.Entity.Internal.LazyInternalContext.Sa veChanges()
at System.Data.Entity.DbContext.SaveChanges()
at CodeFirst_01.Program.Main(String[] args) in D:\New Project\CodeFirst_01\CodeFirst_01\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object state)
at System.Threading.ExecutionContext.RunInternal(Exec utionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Mapping.Update.Internal.Up dateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.Enti tyAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.Enti tyAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.Enti tyAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.Exec uteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.Save ChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionSt rategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.Save ChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.Save Changes(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveCh anges()
InnerException:
Class=16
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=1
Message=The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Number=242
Procedure=""
Server=.
Source=.Net SqlClient Data Provider
State=3
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlExc eption exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnErro r(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndW arning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMeta Data()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteRead er(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderT ds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader( CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataRead er(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(Command Behavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbC ommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.Int ernalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbC ommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand .ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(Command Behavior behavior)
at System.Data.Entity.Core.Mapping.Update.Internal.Dy namicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.Up dateTranslator.Update()
InnerException:

ژیار رحیمی
چهارشنبه 06 مرداد 1395, 23:28 عصر
اگر خطای داخلی بزاری InnerExption میشه فهمید دلیل خطا از چی هست ولی آنچه که از تصویر مشخه کد های Insert شما صحیح میباشد تنها دلیلی که الان به ذهنم میرسه Primary Key شما هست که برای Student ست کردی اگر Auto Increment نیست شما باید موقع درج رکورد کلید رکورد هم وارد کنی (StudentId)

مهیار.
چهارشنبه 06 مرداد 1395, 23:51 عصر
اگر خطای داخلی بزاری InnerExption میشه فهمید دلیل خطا از چی هست ولی آنچه که از تصویر مشخه کد های Insert شما صحیح میباشد تنها دلیلی که الان به ذهنم میرسه Primary Key شما هست که برای Student ست کردی اگر Auto Increment نیست شما باید موقع درج رکورد کلید رکورد هم وارد کنی (StudentId)
ممنون مرسی ... اشتباه از سایت http://www.entityframeworktutorial.net/ بود! منم چک نکرده بودم کدرو ! جایی Student ،Standard جایی گذاری کرده بود :||