1) Enttiy Class In があり、コードが以下に示されている 3 つのテーブルがあります。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Web;
namespace GridWithInlineEdit.Models
{
#region ENTITY BLOCK
[Table("TBLUSER", Schema = "orient")]
public class Users
{
public Users()
{
UsersDetailCollection = new List<Usersdetail>();
}
//
[Key, Column("UID", TypeName = "INT")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Uid { get; set; }
[Required]
[StringLength(50, MinimumLength = 10, ErrorMessage = "Please Enter {0} Upto 50 Characters!")]
[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed here!")]
[Column("FNAME", TypeName = "nvarchar")]
public string Fname { get; set; }
[Required]
[StringLength(100, MinimumLength = 10, ErrorMessage = "Please Enter {0} Upto 50 Characters!")]
[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed here!")]
[Column("LNAME", TypeName = "nvarchar")]
public string Lname { get; set; }
public ICollection<Usersdetail> UsersDetailCollection { get; set; }
}
[Table("TBLUSERDETAIL", Schema = "orient")]
public class Usersdetail
{
public Usersdetail()
{
CountryCollection = new List<Countries>();
}
[Key, Column("ID", TypeName = "INT")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(100)]
[Column("EMAIL", TypeName = "VARCHAR")]
public String Email { get; set; }
[StringLength(11)]
[Column("PHONE", TypeName = "VARCHAR")]
public String Phone { get; set; }
[Required]
public int? UserId { get; set; }
[ForeignKey("UserId"), Column("UID", TypeName = "INT")]
public virtual Users Users { get; set; }
[Required]
public int? CountryId { get; set; }
[ForeignKey("CountryId"), Column("CID", TypeName = "INT")]
public virtual Countries Countries { get; set; }
public ICollection<Countries> CountryCollection { get; set; }
}
[Table("TBLCOUNTRY", Schema = "orient")]
public class Countries
{
[Key, Column("CID", TypeName = "INT")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Cid { get; set; }
[StringLength(50)]
[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed here!")]
[Column("CNAME", TypeName = "VARCHAR")]
public String Cname { get; set; }
}
#endregion
#region ENTITY MAPPING BLOCK
public class UserMap : EntityTypeConfiguration<Users>
{
#region Constructors and Destructors
internal UserMap()
{
// Primary Key
HasKey(t => t.Uid);
Property(p => p.Uid).HasColumnName("UID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
// Table & Column Mappings
ToTable("TBLUSER");
Property(t => t.Fname).HasColumnName("FNAME").HasMaxLength(50);
Property(t => t.Lname).HasColumnName("LNAME").HasMaxLength(50);
}
#endregion
}
public class UserDetailMap : EntityTypeConfiguration<Usersdetail>
{
#region Constructors and Destructors
internal UserDetailMap()
{
// Primary Key
HasKey(t => t.ID);
HasKey(t => t.UserId);
HasKey(t => t.CountryId);
// Properties
Property(t => t.Email).HasMaxLength(100);
Property(t => t.Phone).HasMaxLength(11);
// Column Mappings
ToTable("TBLUSERDETAIL");
Property(t => t.ID).HasColumnName("ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(t => t.Email).HasColumnName("EMAIL");
Property(t => t.Phone).HasColumnName("PHONE");
Property(t => t.UserId).HasColumnName("UID");
Property(t => t.CountryId).HasColumnName("CID");
// Relationships
HasOptional(t => t.Users).WithMany().HasForeignKey(d => d.UserId);
HasOptional(t => t.Countries).WithMany().HasForeignKey(d => d.CountryId);
}
#endregion
}
public class CountryMap : EntityTypeConfiguration<Countries>
{
#region Constructors and Destructors
internal CountryMap()
{
// Primary Key
HasKey(t => t.Cid);
// Properties
Property(t => t.Cname).HasMaxLength(50);
// Column Mappings
Property(t => t.Cid).HasColumnName("CID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(t => t.Cname).HasColumnName("CNAME");
}
#endregion
}
#endregion
}
2) 2 番目は、sqlserver 2005 でカスタム接続文字列を持つ Init クラスです。
接続文字列クラス コードは以下のとおりです。
using System;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
namespace GridWithInlineEdit.Models
{
public static class Constants
{
public static string ConnectionString
{
get { return GetDecryptedConnectionString(); }
}
private static string GetDecryptedConnectionString()
{
return @"Data Source=193.193.193.254;Initial Catalog=EFCFUsersdb;;USER ID=sa;PASSWORD=123;Persist Security Info=True";
}
}
class EncryptedIDbConnectionFactory : IDbConnectionFactory
{
#region Private Fields
IDbConnectionFactory _connectionFactory;
#endregion
#region Constructors
public EncryptedIDbConnectionFactory(IDbConnectionFactory dbConnectionFactory)
{
if (dbConnectionFactory == null)
{
throw new ArgumentNullException("dbConnectionFactory can not be null");
}
_connectionFactory = dbConnectionFactory;
}
#endregion
#region IDbConnectionFactory implementation
public DbConnection CreateConnection(string nameOrConnectionString)
{
//decryption of connection string
string decryptedConnectionString =
GetDecryptedConnectionString(nameOrConnectionString);
return _connectionFactory.CreateConnection(decryptedConnectionString);
}
#endregion
#region Private Methods
private string GetDecryptedConnectionString(string nameOrConnectionString)
{
//use some encryption library to decrypt
return nameOrConnectionString;
}
#endregion
}
}
Initクラスは以下のとおりです
using System.Data.Entity;
namespace GridWithInlineEdit.Models
{
public class Init : DropCreateDatabaseIfModelChanges<SampleContext>
{
protected override void Seed(SampleContext context)
{
base.Seed(context);
//context.Locations.Add(new Location() { LocationName = "Khanna, LDH" });
//context.Sessions.Add(new Session() { SessionName = "Entity Framework" });
context.SaveChanges();
}
}
}
3 ) これは samplecontext クラスのコードです
using System.Data.Entity;
using System.Data.SqlClient;
namespace GridWithInlineEdit.Models
{
public class SampleContext : DbContext
{
public SampleContext()
: base(new SqlConnection(Constants.ConnectionString) ,false)
//Data Source=193.193.193.254;Initial Catalog=EFCFUsersdb;Persist Security Info=True;User ID=sa;Password=123
{
Configuration.ProxyCreationEnabled = true;
Configuration.AutoDetectChangesEnabled = true;
}
public DbSet<Users> User { get; set; }
public DbSet<Usersdetail> UserDetail { get; set; }
public DbSet<Countries> Country { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new UserDetailMap());
modelBuilder.Configurations.Add(new CountryMap());
}
}
}
4) アプリケーションのグローバル ファイルには、以下のコードがあります。
using System.Data.Entity;
using System.Web.Mvc;
using System.Web.Routing;
using GridWithInlineEdit.Models;
namespace GridWithInlineEdit
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "User", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
//Database.DefaultConnectionFactory = new EncryptedIDbConnectionFactory(Database.DefaultConnectionFactory);
Database.SetInitializer<SampleContext>(new Init());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
My Home Controller には、以下のコードがあります
> 1. using System.Web.Mvc; using GridWithInlineEdit.Models;
>
> namespace GridWithInlineEdit.Controllers {
> public class UserController : Controller
> {
>
>
> public ActionResult Index()
> {
> var db = new SampleContext();
> return View();
> }
>
> [HttpPost]
> public ActionResult Create()
> {
>
> //return View();
> return null;
> }
>
> } }
ここでの問題は、アプリケーション データベースが作成されず、インデックス アクションの結果にブレークポイントを設定して _db オブジェクトにウォッチを追加すると、例外サーバー バージョン プロパティが表示されるたびに発生することです。pls pls 解決するか解決策を教えてください。私はこれまで何度も試してきましたが、なぜこれが起こったのか混乱しています