MVC实现EF模型随意切换(四)学习

DAL层

 public class BaseDal<T> where T : class , new()
        private DbContext db = EFDbcontextFactory.GetcurrentDbcontext();


创建类

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Dulei.Model;


namespace Dulei.DAL
{
     public class EFDbcontextFactory
    {
         public static DbContext GetcurrentDbcontext()
         {
             //可以直接对Model模型进行切换。只要更改DataModelContainer()
             return new DataModelContainer();
         }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个基于MVCEF的文件上传代码示例: 1. 在MVC中创建一个上传文件的视图(View)和控制器(Controller): View代码: ```html @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="file" /> <input type="submit" value="Upload" /> } ``` Controller代码: ```csharp public class HomeController : Controller { private readonly ApplicationDbContext _context; public HomeController(ApplicationDbContext context) { _context = context; } public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> UploadFile(IFormFile file) { if (file == null || file.Length == 0) return Content("file not selected"); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads", file.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } var fileModel = new FileModel() { FileName = file.FileName, FilePath = filePath }; _context.FileModels.Add(fileModel); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } } ``` 2. 创建一个FileModel类作为上传的文件记录,用于在数据库中存储上传的文件信息: ```csharp public class FileModel { public int Id { get; set; } public string FileName { get; set; } public string FilePath { get; set; } } ``` 3. 在EF中创建一个DBContext类(ApplicationDbContext),用于连接数据库并映射FileModel类: ```csharp public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<FileModel> FileModels { get; set; } } ``` 4. 在Startup类中配置数据库连接和EF: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllersWithViews(); } ``` 5. 在appsettings.json文件中添加数据库连接字符串: ```json "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FileUploadDb;Trusted_Connection=True;MultipleActiveResultSets=true" } ``` 6. 最后,在wwwroot目录下创建一个uploads文件夹,用于保存上传的文件。 这样,当用户选择文件并点击“Upload”按钮时,文件将被保存在服务器上,并在数据库中创建一个新的FileModel记录。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值