EF 常见语句以及sql语句简单 后续继续添加

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()
{
#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>

时间: 2024-11-05 01:56:48

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

DbCommandInterceptor抓取EF执行时的SQL语句

EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.Entity.Infrastructure.Interception 命名空间,此命名空间下的对象可以允许我们更加方便的了解到EF运行时的一些信息,当然我们最想看的还是EF生成的Sql语句,话不多讲,开始干吧; /// <summary> /// 抓取EF执行时的SQL语句 /// </summary> public class EFIntercepterLogging : DbComman

一句话,将Linq语句转换为Sql语句

 public IEnumerable<VMB_Report> ReportView_List(VMB_ReportConditions requiredModel) { IEnumerable<VMB_Report> resultModel = new List<VMB_Report>(); IQueryable<Merchant> merchantList; merchantList = Report_List(); #region 从Merchan

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

h4 { padding: 8px 5px; background-color: #32c5d2 } .start-box,.body { padding: 10px } .tit { font-size: 14px; font-weight: bold } div.content { line-height: 150%; font-weight: bold } .content { border: dashed 1px #999999; padding: 10px; background: #

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

一.目前EF Core的版本为V2.1 相比较EF Core v1.0 目前已经增加了不少功能. EF Core除了常用的增删改模型操作,Sql语句在不少项目中是不能避免的. 在EF Core中上下文,可以返货DbConnection ,执行sql语句.这是最底层的操作方式,代码写起来还是挺多的. 初次之外 EF Core中还支持 FromSql,ExecuteSqlCommand 连个方法,用于更方便的执行Sql语句. 另外,目前版本的EF Core 不支持SqlQuery,但是我们可以自己扩

在EF中直接执行SQL语句

最近考虑到并发的问题,用 EF 处理并发非常麻烦, 直接用原生SQL简单: Database.ExecuteSqlCommand:不用返回结果,比如Update等等, Database.SqlQuery<T>:返回结果,比如查询 例: db.Database.ExecuteSqlCommand("update tbMemberAccount set Sum_Recharge=Sum_Recharge+{0},Left_ECurrency=Left_ECurrency+{0},Upda

asp.net EF框架执行原生SQL语句

1.执行无参数sql: string sql = "select * from IntegralInfo where convert(nvarchar,getdate(),23)='{0}' and status=1 and userinfoid='{1}'"; sql = string.Format(sql, DateTime.Now.ToString("yyyy-MM-dd"), uid); var IntegralInfoObj = db.Database.S

EF Code 如何输出sql语句

首先写拷贝下面类 public class EFLoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName); public void Dispose() { } } public class EFLogger : ILogger { private readonly string categoryName; public EFLo

mysql语句与sql语句的基本区别

1. MySQL支持enum和set类型,SQL Server不支持: 2. MySQL不支持nchar.nvarchar.ntext类型: 3. MySQL数据库的递增语句是AUTO_INCREMENT,而MS SQL是identity(1,1): 4. MS SQL默认到处表创建语句的默认值表示是((0)),而在MySQL里面是不允许带两括号的: 5. MySQL需要为表指定存储类型: 6. MS SQL识别符是[],[type]表示他区别于关键字,但是MySQL却是 `,也就是按键1左边的

mongodb 语句和SQL语句对应(SQL to Aggregation Mapping Chart)

SQL to Aggregation Mapping Chart https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/ On this page Examples Additional Resources The aggregation pipeline allows MongoDB to provide native aggregation capabilities that corresponds to m