1.注意级联删除的时候数据库的外键要设置为开启级联删除,(数据库里sqlserver的外键修改的时候,可以看到级联删除和级联更新)

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{

//EF 批量添加10万数据,虽然表格只有4个列,但是耗时却大概只有1分钟,足见效率已经提高了很多

Model1Container context=new Model1Container();
Class c = context.Classes.First(x => x.Id == 1);
Student s = null;
List<Student> stuList=new List<Student>();
for (int i = 10; i < 10; i++)
{
s = new Student() { Address = i.ToString(), Class = c, Name = i.ToString() + "N" };
stuList.Add(s);
}

//这里使用AddRange经过我测试效率会比直接在循环内context.Students.Add(s)的效率高非常多

context.Students.AddRange(stuList);
context.SaveChanges();

Class c2 = context.Classes.First(x=>x.Id==1);

//ef的修改

Menu m2=new Menu() {mId = 119,mName = "151"};
dbContext.Menus.Attach(m2);
dbContext.Entry(m2).State=EntityState.Modified;
dbContext.SaveChanges();

//ef的修改

//如果只想针对性的修改某几列提高效率就这样

Menu m2=new Menu() {mId = 119,mName = "1511"};
dbContext.Menus.Attach(m2);
dbContext.Entry(m2).State=EntityState.Unchanged;
dbContext.Entry(m2).Property("mName").IsModified = true;
dbContext.SaveChanges();

#region EF的添加代码,这里是一个一对多的关系
//Model1Container DbContext = new Model1Container();
//User u = new User() { UserName = "zhangsan" };
//Role r = new Role() { RoleName = "juese1" };
//u.Role = new List<Role>();
//DbContext.Entry(r).State = System.Data.Entity.EntityState.Added;
//u.Role.Add(r);
//DbContext.Users.Add(u);
//DbContext.SaveChanges();
#endregion

#region 级联删除
// < Association Name = "UserRole" >
// < End Type = "Model1.User" Role = "User" Multiplicity = "1" >
// < OnDelete Action = "Cascade" /> 注意如果是1对1的话在配置文件edmx中设置为级联删除开启,1对多,多对多默认是开启的
// </ End >
// < End Type = "Model1.Role" Role = "Role" Multiplicity = "*" />
// </ Association >
#region 非官方推荐的删除
//官方推荐的删除方式是先查询再删除,而这里的是通过附加ef上下文去删除,有个问题如果当前的对象id不存在就会报错
//这就是为什么官方推荐先查询再删除的原因,查询之后你可以判断对象是不是为空
//Model1Container DbContext = new Model1Container();
//User u = new User() { Id = 2 };
//DbContext.Users.Attach(u);
//DbContext.Users.Remove(u);
//DbContext.SaveChanges();
#endregion

#region 官方推荐的删除方式
//官方推荐的删除方式
//Model1Container DbContext = new Model1Container();
//User u = DbContext.Users.FirstOrDefault(x => x.Id == 2);
//if (u != null)
// DbContext.Users.Remove(u);
//DbContext.SaveChanges();
#endregion

#endregion

#region EF-SQL语句
Model1Container DbContext=new Model1Container();
int i=DbContext.Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction,
"update users set username='李四' where id=3");
#endregion

return View();
}
}
}

2.顺带的生成的类我也一起贴进来吧

namespace WebApplication3.Models
{
using System;
using System.Collections.Generic;

public partial class Role
{
public int Id { get; set; }
public string RoleName { get; set; }

public virtual User User { get; set; }
}
}

//------------------------------------------------------------------------------
// <auto-generated>
// 此代码已从模板生成。
//
// 手动更改此文件可能导致应用程序出现意外的行为。
// 如果重新生成代码,将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebApplication3.Models
{
using System;
using System.Collections.Generic;

public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Role = new HashSet<Role>();
}

public int Id { get; set; }
public string UserName { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Role> Role { get; set; }
}
}

3.我把配置文件一起贴这里,其实可以根据图形界面操作生成,这里也必须知道原理,不然无法更改

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="Model1.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityContainer Name="Model1StoreContainer">
<EntitySet Name="Users" EntityType="Model1.Store.Users" store:Type="Tables" Schema="dbo" />
<EntitySet Name="Roles" EntityType="Model1.Store.Roles" store:Type="Tables" Schema="dbo" />
<AssociationSet Name="UserRole" Association="Model1.Store.UserRole">
<End Role="User" EntitySet="Users" />
<End Role="Role" EntitySet="Roles" />
</AssociationSet>
</EntityContainer>
<EntityType Name="Users">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="UserName" Type="nvarchar(max)" Nullable="false" />
</EntityType>
<EntityType Name="Roles">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="RoleName" Type="nvarchar(max)" Nullable="false" />
<Property Name="Uid" Type="int" Nullable="false" />
</EntityType>
<Association Name="UserRole">
<End Role="User" Type="Model1.Store.Users" Multiplicity="1" />
<End Role="Role" Type="Model1.Store.Roles" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="User">
<PropertyRef Name="Id" />
</Principal>
<Dependent Role="Role">
<PropertyRef Name="Uid" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema></edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="Model1" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" annotation:UseStrongSpatialTypes="false">
<EntityContainer Name="Model1Container" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Users" EntityType="Model1.User" />
<EntitySet Name="Roles" EntityType="Model1.Role" />
<AssociationSet Name="UserRole" Association="Model1.UserRole">
<End Role="User" EntitySet="Users" />
<End Role="Role" EntitySet="Roles" />
</AssociationSet>
</EntityContainer>
<EntityType Name="User">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="UserName" Type="String" Nullable="false" />
<NavigationProperty Name="Role" Relationship="Model1.UserRole" FromRole="User" ToRole="Role" />
</EntityType>
<EntityType Name="Role">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="RoleName" Type="String" Nullable="false" />
<NavigationProperty Name="User" Relationship="Model1.UserRole" FromRole="Role" ToRole="User" />
</EntityType>
<Association Name="UserRole">
<End Type="Model1.User" Role="User" Multiplicity="1" >
<!--<OnDelete Action="Cascade"/>-->

</End>
<End Type="Model1.Role" Role="Role" Multiplicity="*" />

</Association>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="Model1StoreContainer" CdmEntityContainer="Model1Container">
<EntitySetMapping Name="Users">
<EntityTypeMapping TypeName="IsTypeOf(Model1.User)">
<MappingFragment StoreEntitySet="Users">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="UserName" ColumnName="UserName" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="Roles">
<EntityTypeMapping TypeName="IsTypeOf(Model1.Role)">
<MappingFragment StoreEntitySet="Roles">
<ScalarProperty Name="Id" ColumnName="Id" />
<ScalarProperty Name="RoleName" ColumnName="RoleName" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="UserRole" TypeName="Model1.UserRole" StoreEntitySet="Roles">
<EndProperty Name="User">
<ScalarProperty Name="Id" ColumnName="Uid" />
</EndProperty>
<EndProperty Name="Role">
<ScalarProperty Name="Id" ColumnName="Id" />
</EndProperty>
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping></edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="False" />
<DesignerProperty Name="CodeGenerationStrategy" Value="无" />
<DesignerProperty Name="UseLegacyProvider" Value="False" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>

3.更能说明问题的edmx

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="Model1.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityContainer Name="Model1StoreContainer">
<EntitySet Name="Classes" EntityType="Model1.Store.Classes" store:Type="Tables" Schema="dbo" />
<EntitySet Name="Students" EntityType="Model1.Store.Students" store:Type="Tables" Schema="dbo" />
<AssociationSet Name="ClassStudent" Association="Model1.Store.ClassStudent">
<End Role="Class" EntitySet="Classes" />
<End Role="Student" EntitySet="Students" />
</AssociationSet>
</EntityContainer>
<EntityType Name="Classes">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="ClassName" Type="nvarchar(max)" Nullable="false" />
<Property Name="ClassNo" Type="nvarchar(max)" Nullable="false" />
<Property Name="DeptNo" Type="nvarchar(max)" Nullable="false" />
</EntityType>
<EntityType Name="Students">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Name" Type="nvarchar(max)" Nullable="false" />
<Property Name="Address" Type="nvarchar(max)" Nullable="false" />
<Property Name="ClassId" Type="int" Nullable="false" />
</EntityType>
<Association Name="ClassStudent">
<End Role="Class" Type="Model1.Store.Classes" Multiplicity="1" />
<End Role="Student" Type="Model1.Store.Students" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Class">
<PropertyRef Name="Id" />
</Principal>
<Dependent Role="Student">
<PropertyRef Name="ClassId" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema></edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="Model1" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" annotation:UseStrongSpatialTypes="false">
<EntityContainer Name="Model1Container" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Classes2" EntityType="Model1.Class2" />
<EntitySet Name="Students2" EntityType="Model1.Student2" />
<AssociationSet Name="ClassStudent" Association="Model1.ClassStudent">
<End Role="Class" EntitySet="Classes2" />
<End Role="Student" EntitySet="Students2" />
</AssociationSet>
</EntityContainer>
<EntityType Name="Class2">
<Key>
<PropertyRef Name="Id2" />
</Key>
<Property Name="Id2" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="ClassName2" Type="String" Nullable="false" />
<Property Name="ClassNo2" Type="String" Nullable="false" />
<Property Name="DeptNo2" Type="String" Nullable="false" />
<NavigationProperty Name="DaoStudent" Relationship="Model1.ClassStudent" FromRole="Class" ToRole="Student" />
</EntityType>
<EntityType Name="Student2">
<Key>
<PropertyRef Name="Id2" />
</Key>
<Property Name="Id2" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="StuName2" Type="String" Nullable="false" />
<Property Name="Address2" Type="String" Nullable="false" />
<NavigationProperty Name="DaoClass" Relationship="Model1.ClassStudent" FromRole="Student" ToRole="Class" />
<Property Name="ClassId" Type="Int32" Nullable="false" />
</EntityType>
<Association Name="ClassStudent">
<End Type="Model1.Class2" Role="Class" Multiplicity="1" />
<End Type="Model1.Student2" Role="Student" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Class">
<PropertyRef Name="Id2" />
</Principal>
<Dependent Role="Student">
<PropertyRef Name="ClassId" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="Model1StoreContainer" CdmEntityContainer="Model1Container">
<EntitySetMapping Name="Classes2">
<EntityTypeMapping TypeName="IsTypeOf(Model1.Class2)">
<MappingFragment StoreEntitySet="Classes">
<ScalarProperty Name="Id2" ColumnName="Id" />
<ScalarProperty Name="ClassName2" ColumnName="ClassName" />
<ScalarProperty Name="ClassNo2" ColumnName="ClassNo" />
<ScalarProperty Name="DeptNo2" ColumnName="DeptNo" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="Students2">
<EntityTypeMapping TypeName="IsTypeOf(Model1.Student2)">
<MappingFragment StoreEntitySet="Students">
<ScalarProperty Name="Id2" ColumnName="Id" />
<ScalarProperty Name="StuName2" ColumnName="Name" />
<ScalarProperty Name="Address2" ColumnName="Address" />
<ScalarProperty Name="ClassId" ColumnName="ClassId" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping></edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<edmx:Designer xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
<edmx:Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</edmx:Connection>
<edmx:Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="False" />
<DesignerProperty Name="CodeGenerationStrategy" Value="无" />
<DesignerProperty Name="UseLegacyProvider" Value="False" />
</DesignerInfoPropertySet>
</edmx:Options>
<!-- Diagram content (shape and connector positions) -->
<edmx:Diagrams>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>

EF 常见语句以及sql语句简单 后续继续添加的更多相关文章

  1. .NET Core实用技巧(一)如何将EF Core生成的SQL语句显示在控制台中

    目录 .NET Core实用技巧(一)如何将EF Core生成的SQL语句显示在控制台中 前言 笔者最近在开发和维护一个.NET Core项目,其中使用几个非常有意思的.NET Core相关的扩展,在 ...

  2. DbCommandInterceptor抓取EF执行时的SQL语句

    EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.Entity.Infrastructure.Interception 命名空间,此命名空间下的对象可以允许我 ...

  3. EF Core 日志跟踪sql语句

    EF Core 日志跟踪sql语句 官方文档链接:https://docs.microsoft.com/en-us/ef/core/miscellaneous/logging 1.新增自定义ILogg ...

  4. 如果一条SQL语句太长,我们可以通过回车键来创建一个新行来编写SQL语句,SQL语句的命令结束符为分号(;)。

    1.如果一条SQL语句太长,我们可以通过回车键来创建一个新行来编写SQL语句,SQL语句的命令结束符为分号(;). 2.select查询的多个字段之间要用逗号“,”分割,如果查询涉及多个表,那多个表之 ...

  5. EF Core中执行Sql语句查询操作之FromSql,ExecuteSqlCommand,SqlQuery

    一.目前EF Core的版本为V2.1 相比较EF Core v1.0 目前已经增加了不少功能. EF Core除了常用的增删改模型操作,Sql语句在不少项目中是不能避免的. 在EF Core中上下文 ...

  6. Asp.Net MVC EF之一:使用Database类在EF框架中执行Sql语句

    引言 从EF6开始,增加了DateBase类,他通过从 DbContext 对象获取此类的实例.可用于管理支持数据库上下文或连接的实际数据库.这包括创建.删除和检查数据库的存在. 在6以前,我们使用E ...

  7. EF 记录执行的sql语句

    最近做了个中等的项目,数据不会很多,开发时间比较紧迫,所以用了EF的框架. 在使用过程中,发现有时候执行的结果不如预期,想看看执行的sql语句为何,遍查找资料,在网上找到了相关辅助类,拿来使用,部署到 ...

  8. mongodb查询语句与sql语句对比

    左边是mongodb查询语句,右边是sql语句.对照着用,挺方便. db.users.find() select * from users db.users.find({"age" ...

  9. 关于EF中直接执行sql语句的参数化问题

    某天 , 在review项目中代码的时候, 发现有哥们直接通过 Database.ExecuteSqlCommand("select * from order_info where  com ...

随机推荐

  1. 洛谷 P1292 倒酒

    题目描述 Winy是一家酒吧的老板,他的酒吧提供两种体积的啤酒,a ml和b ml,分别使用容积为a ml和b ml的酒杯来装载. 酒吧的生意并不好.Winy发现酒鬼们都非常穷.有时,他们会因为负担不 ...

  2. sqlalchemy在pythonweb中开发的使用(基于tornado的基础上)

    一.关于SQLAlchemy的安装pip install SQLAlchemy安装如果上面的方式安装不成功的情况可以使用下面的方法 百度下载window或者linux下面对应的sqlalchemy的版 ...

  3. 几个开源faas 框架

    funktion open source event based lambda programming for kubernetes 官方地址: funktion.fabric8.io serverl ...

  4. pidstat

    统计系统上的某个进程占用的磁盘读写 pidstat -d   -p   pidNumber  3 -d  表示磁盘设备 -p 指定pid 3 表示每三秒刷新一次结果

  5. 【转】Jmeter做功能测试的优点和不足

    利用Jmeter做功能测试有以下优点: ●    不依赖于界面,如果服务正常启动,传递参数明确就可以添加测试用例,执行测试 ●    测试脚本不需要编程,熟悉http请求,熟悉业务流程,就可以根据页面 ...

  6. java流类,快速统计出字符次数+++

    总结:学会给一个合适的命名,不要总是abc..虽然简单,但是不容易看懂,和方便去理解 package com.aini; import java.io.File; import java.io.Fil ...

  7. 1107 Social Clusters

    题意:给出n个人(编号为1~n)以及每个人的若干个爱好,把有一个或多个共同爱好的人归为一个集合,问共有多少个集合,每个集合里有多少个人? 思路:典型的并查集题目.并查集的模板init()函数,unio ...

  8. [置顶] STM32的ADC1采集多条通道,可以不使用DMA功能吗?

    类似的问题 为什么我采集5条通道的电压,而采集到的值却都是第一条的呢? 我什么时候需要使用DMA功能? Ⅰ关于ADC的一些知识 STM32的ADC是一种12位逐次逼近型的模拟数字转换器.它有多达18条 ...

  9. 移植OpenWrt到CuHead Pro WiFi

    移植OpenWrt到CuHead Pro WiFi Posted by: zou, baozhu , 三月 13, 2014 CuHead Pro是一款路由器开发板,下面是开发板的配置信息. 名称 型 ...

  10. 命令提示符(cmd)中的tracert命令详解(小技巧)

    tracert也被称为Windows路由跟踪实用程序,在命令提示符(cmd)中使用tracert命令可以用于确定IP数据包访问目标时所选择的路径.本文主要探讨了tracert命令的各个功能. 百度经验 ...