gpt4 book ai didi

entity-framework - 有没有办法删除MVC 4中对Entity Framework的默认依赖关系?

转载 作者:行者123 更新时间:2023-12-04 13:33:07 24 4
gpt4 key购买 nike

有没有一种方法可以删除ASP.NET MVC 4项目中对Entity Framework的默认依赖关系,并将其替换为另一种类似的技术,例如Dapper

最佳答案

如果您创建一个新的ASP.NET MVC 4 Web应用程序并选择“Internet应用程序”作为项目模板,您会注意到 Entity Framework 已被引用并用作SimpleMembership的一部分。但是,对Entity Framework的依赖很小,可能不值得删除它。
Entity Framework 似乎仅用于2个次要任务
使用 Entity Framework 的第一种方法是创建存储成员资格数据所需的数据库架构。 Dapper不会为您创建数据库架构,如果删除Entity Framework,则必须手动管理对成员资格模型/数据库的更改。
使用Entity Framework的第二种方法是在默认的“AccountController”内部的一个名为“ExternalLoginConfirmation”的方法中,作为其OAuth集成的一部分。它用于注册已从外部提供商(例如Facebook)进行身份验证的新用户。
那么我们可以说SimpleMembership使用SQL命令而不使用Entity Framework [1]。
因为SimpleMembership使用SQL命令而不使用Entity Framework,所以它应该与与此任务类似的Dapper解决方案一样快。此外,Microsoft和社区已经对该配置SimpleMembership进行了广泛的测试。由于这些原因,我将不理会它。有关安全性的代码应留给经过认证的安全专家[2]。
如何从新的ASP.NET MVC 4 Web应用程序中删除 Entity Framework
如果确实需要,则依赖关系很容易删除(我假设您的成员(member)数据库已经创建并且可以正常工作)。
=====> 步骤1
在Visual Studio解决方案资源管理器中,打开“引用”文件夹。
右键单击“EntityFramework”,然后选择“删除”。
=====> 步骤2
打开过滤器/InitializeSimpleMembershipAttribute.cs
删除以下内容:

using System.Data.Entity.Infrastructure;
Database.SetInitializer<UsersContext>( null );
using ( var context = new UsersContext() ) {
if ( !context.Database.Exists() ) {
// Create the SimpleMembership database without Entity Framework migration schema
( ( IObjectContextAdapter ) context ).ObjectContext.CreateDatabase();
}
}
=====> 步骤3
打开:Models/AccountModels.cs
删除以下内容:
public class UsersContext : DbContext {
public UsersContext()
: base( "DefaultConnection" ) {
}

public DbSet<UserProfile> UserProfiles {
get;
set;
}
}
=====> 步骤4
打开:Controllers/AccountController.cs
查找名为“ExternalLoginConfirmation”的方法。
替换以下内容:
using ( UsersContext db = new UsersContext() ) {
UserProfile user = db.UserProfiles.FirstOrDefault( u => u.UserName.ToLower() == model.UserName.ToLower() );
// Check if user already exists
if ( user == null ) {
// Insert name into the profile table
db.UserProfiles.Add( new UserProfile {
UserName = model.UserName
} );
db.SaveChanges();
使用等效的精巧代码-这些代码注释会告诉您需要实现什么。
如果您不使用OAuth,则应该可以完全删除此方法和其他方法。
Et Voila;)

[1] "Everything's implemented as SQL calls rather than requiring stored procedures, views, agents, and change notifications."
Jon Galloway, Microsoft

[2] "Let me give you all my standard caution about rolling your own cryptographic algorithms and security systems: don't. It is very, very easy to create security systems which are almost but not quite secure. A security system which gives you a false sense of security is worse than no security system at all!"
Eric Lippert, Legend

关于entity-framework - 有没有办法删除MVC 4中对Entity Framework的默认依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com