EF Code First #1
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۲/۱۴ ۱۰:۰۷:۰۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="4.3.1" />
</packages>
<?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.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
namespace EF_Sample01.Models
{
public class Post
{
public int Id { set; get; }
public string Title { set; get; }
public string Content { set; get; }
public virtual Blog Blog { set; get; }
}
}
using System.Collections.Generic;
namespace EF_Sample01.Models
{
public class Blog
{
public int Id { set; get; }
public string Title { set; get; }
public string AuthorName { set; get; }
public IList<Post> Posts { set; get; }
}
}
using System.Data.Entity;
using EF_Sample01.Models;
namespace EF_Sample01
{
public class Context : DbContext
{
public DbSet<Blog> Blogs { set; get; }
public DbSet<Post> Posts { set; get; }
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
</configSections>
<connectionStrings>
<clear/>
<add name="Context"
connectionString="Data Source=(local);Initial Catalog=testdb2012;Integrated Security = true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
...
</configuration>
<connectionStrings>
<add name="MyContextName"
connectionString="Data Source=|DataDirectory|\Store.sdf"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
public class Context : DbContext
{
public Context()
: base("ConnectionStringName")
{
}
using EF_Sample01.Models;
namespace EF_Sample01
{
class Program
{
static void Main(string[] args)
{
using (var db = new Context())
{
db.Blogs.Add(new Blog { AuthorName = "Vahid", Title = ".NET Tips" });
db.SaveChanges();
}
}
}
}
using EF_Sample01.Models;
namespace EF_Sample01
{
class Program
{
static void Main(string[] args)
{
//addBlog();
addPost();
}
private static void addPost()
{
using (var db = new Context())
{
var blog = db.Blogs.Find(1);
db.Posts.Add(new Post
{
Blog = blog,
Content = "data",
Title = "EF"
});
db.SaveChanges();
}
}
private static void addBlog()
{
using (var db = new Context())
{
db.Blogs.Add(new Blog { AuthorName = "Vahid", Title = ".NET Tips" });
db.SaveChanges();
}
}
}
}
exec sp_executesql N'insert [dbo].[Posts]([Title], [Content], [Blog_Id])
values (@0, @1, @2)
select [Id]
from [dbo].[Posts]
where @@ROWCOUNT > 0 and [Id] = scope_identity()',
N'@0 nvarchar(max) ,@1 nvarchar(max) ,@2 int',
@0=N'EF',
@1=N'data',
@2=1
Cannot open database "EFTest" requested by the login. The login failed.
<connectionStrings>
<clear/>
<add
name="ProductContext"
connectionString="Data Source=(local);Initial Catalog=testdb2012;Integrated Security = true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
public class ProductContext : DbContext
Could not install package 'EntityFramework 4.3.1'. You are trying to install this package into a project that targets 'Silverlight,Version=v5.0', but the package does not contain any assembly references that are compatible with that framework.
سلام ممنون از مطالب مفیدتون
من تازه 1 روزه شروع کردم code first کار کنم
تو یه مقاله داشتم میخوندم برای تعریف entity ها این association ها رو تو هر دو طرف virtual تعریف کرده بود
مثلا برای blog این طور نوشته بود
public virtual IList<post> posts { set; get; }
خودم هم این طور نوشتم تا این جا که فرقی ندیدم میشه توضیح بدید چه فرقی دارن
باز هم ممنونم
using System;
using System.Collections.Generic;
namespace ChapterOneProject
{
public class Patient
{
public Patient()
{
Visits = new List<Visit>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
//[ForeignKey("AnimalTypeId")]
public AnimalType AnimalType { get; set; }
//public int AnimalTypeId { get; set; }
public DateTime FirstVisit { get; set; }
public List<Visit> Visits { get; set; }
}
public class Visit
{
[Key]
public int Id { get; set; }
public DateTime Date { get; set; }
public String ReasonForVisit { get; set; }
public String Outcome { get; set; }
public Decimal Weight { get; set; }
//[ForeignKey("PatientId")]
//public virtual Patient Patient { get; set; }
public int PatientId { get; set; }
}
public class AnimalType
{
public int Id { get; set; }
public string TypeName { get; set; }
}
}public class VetContext : DbContext
{
public DbSet<Patient> Patients { get; set; }
public DbSet<Visit> Visits { get; set; }
//public DbSet<AnimalType> AnimalTypes { get; set; }
}var dog = new AnimalType { TypeName = "Dog" };
var visit = new List<Visit>
{
new Visit
{
Date = new DateTime(2011, 9, 1),
Outcome = "Test",
ReasonForVisit = "Test",
Weight = 32,
}
};
var patient = new Patient
{
Name = "Sampson",
BirthDate = new DateTime(2008, 1, 28),
AnimalType = dog,
Visits = visit,
};
using (var context = new VetContext())
{
context.Patients.Add(patient);
context.SaveChanges();
}.... BirthDate = new DateTime(2008, 1, 28), <<< FirstVisit = new DateTime(2008,1,12), >>> AnimalType = dog, .....
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<configuration> <configSections> </configSections> <connectionStrings> <clear/> <add name="Context" connectionString="Data Source=localhost;Initial Catalog=test;Integrated Security = true" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <compilation debug="true"/></system.web> </configuration>
<add name="Context"
connectionString="Data Source=.\sql2012;Initial Catalog=testdb2012;Integrated Security = true"
providerName="System.Data.SqlClient"
/> public class Blog
{
public int Id { set; get; }
public string Title { set; get; }
public string AuthorName { set; get; }
public IList<Post> Posts { set; get; }
} get
{
return ?
}
set
{
//push calculated private field to db ?
}
Install-Package : Could not connect to the feed specified at 'https://www.nuget.org/api/v2/'. Please verify that the package source
(located in the Package Manager Settings) is valid and ensure your network connectivity.
At line:1 char:1
+ Install-Package EntityFramework
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand سلام
اگر در سازنده DbContext با مقدار ثابتی مثل base("connectionName") مقداردهی کنیم به کانکشن موردنظر وصل میشود ولی وقتی که این مقدار را Runtime ست میکنم عمل نمیکند و خطا میدهد کانکشن پیدانشد. در حالی که معادل نامی که RunTime ست شده است کانکشن استرینگی تعریف شده است.
var ctx = new MyContext(); ctx.Database.Connection.ConnectionString = "...";
public IList<Post> Posts { set; get; } public ICollection<Post> Posts { set; get; }
db.Entry(message).State = EntityState.Added; db.SaveChanges();
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
} public override void Up()
{
Sql(...);
CreateTable(....);
Sql(....);
} {"Cannot open database \"kashanSchools\" requested by the login. The login failed.\r\nLogin failed for user 'ALIPC\\ali'."} <add name="DefaultConnection" connectionString="Server=. Database=kashanSchools;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
<connectionStrings> <add name="X" connectionString="Data Source=Y;Initial Catalog=DataBaseName;User ID=sa; Password=1234;" providerName="System.Data.SqlClient" /> </connectionStrings>
public Context():base("X")
{
} management studio -> select server -> expand Security -> right click Logins -> select "New Login..."
Right click on db-> properties -> permission -> View Server permission
Server=. Database=kashanSchools;Trusted_Connection=True;
Data Source=(local);Initial Catalog=kashanSchools;Integrated Security = true