简体   繁体   English

我的代码优先方法中的错误我在VS 2010中安装了EF 4.1

[英]Error in my code first approach i have EF 4.1 with VS 2010

1) i have Enttiy Class In which have three tables whose code is below given 1)我有Enttiy类,其中有三个表,其代码如下

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) Second is Init Class in which have connection string custom with sqlserver 2005 2)第二个是Init类,其中具有使用sqlserver 2005自定义的连接字符串

Connection string class code is below given 连接字符串类代码如下

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
    }
}

and Init class is below given 和初始化类低于给定

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 ) this is samplecontext class code 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) in Global file of application have below code 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);
        }
    }

}

In My Home Controller have below given code 在我的家庭控制器中有以下给定的代码

> 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;
>             }
>     
>         } }

Now the problem is this whenever run my application database is not created and show exception server version property when i see through add watch in _db object by putting breakpoint on index action result. 现在的问题是,无论何时未运行我的应用程序数据库,当我通过在索引操作结果上放置断点来查看_db对象中的添加监视时,都显示异常服务器版本属性。 pls pls resolve or give solution i have tried for this many time but i am confused why this happening 请解决或给出解决方案,我已经尝试了很多次,但是我很困惑为什么会这样

I know you have in the comments above that you applied a Windows Server patch and got it working, but with looking at your project, I had some observations: 我知道您在上面的评论中已经应用了Windows Server补丁并使其正常运行,但是在查看您的项目时,我有一些发现:

  • There is nothing in your "Create" method in your controller for adding new records 控制器的“创建”方法中没有添加新记录的内容
  • There is no "Read" method for returning data to anything that might want to read data, such as a Kendo grid. 没有“读取”方法可以将数据返回到可能想要读取数据的任何对象(例如Kendo网格)。
  • There is no "Delete" method for removing data records. 没有用于删除数据记录的“删除”方法。
  • I'm not sure what the UserMap, DetailMap, and CountryMap are used for, along with your "RegisterRoutes", etc. on Application_Start -- these seem like a severe case of overcomplicating things, to me. 我不确定Application_Start上的UserMap,DetailMap和CountryMap以及您的“ RegisterRoutes”等用于什么用途-对我来说,这似乎是一种使情况过于复杂的严重案例。
  • No View (presentation layer) code posted. 没有发布视图(表示层)代码。

Maybe you fixed the Create, Read, and Delete routines later when you got it working, and maybe the UserMap, DetailMap, CountryMap, and Init all were for something, but be damned if I could make heads-or-tails of what you were doing. 也许您稍后在工作时修复了“创建”,“读取”和“删除”例程,也许UserMap,DetailMap,CountryMap和Init都是出于某些目的,但是如果我能对您的工作做些了解,那该死的在做。 I saw no View code, grid or otherwise, that you were pulling your data into. 我没有看到将数据拖入的View代码,网格或其他格式。 When asking for help, just saying, context is everything. 当寻求帮助时,只是说,上下文就是一切。

While you would need to obtain and install Telerik's Kendo UI MVC components, it might be worth it to you to look at this blog for setting up the entity framework in MVC and preparing a grid for receiving data: http://docs.telerik.com/kendo-ui/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding 尽管您需要获取并安装Telerik的Kendo UI MVC组件,但值得看一下此博客,以在MVC中设置实体框架并准备一个网格来接收数据: http://docs.telerik。 com / kendo-ui /入门/使用kendo-with / aspnet-mvc / helpers / grid / ajax-binding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM