1. Note that when cascading is deleted, the foreign key of the database should be set to turn on cascade Delete, (when the foreign key of SQL Server in the database is modified, you can see the cascade Delete and cascade Update)
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 Add-on code, here's a one-to-many relationship
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 Cascade Delete
< association Name = "Userrole" >
< End Type = "Model1.user" Role = "User" multiplicity = "1" >
< OnDelete Action = "Cascade"/> Note if 1 to 1 is set to cascade Delete in Profile edmx on, 1 to many, many to many by default is turned on
</End >
< End Type = "model1.role" role = "role" multiplicity = "*"/>
</Association >
#region Unofficial recommendations for deletion
The official recommended deletion method is to query and then delete, and here is the addition of the EF context to delete, there is a problem if the current object ID does not exist will be an error
This is why the official recommendation first query and then delete the reason, after the query you can determine whether the object is empty
Model1container DbContext = new Model1container ();
User U = New User () {Id = 2};
DbContext.Users.Attach (U);
DbContext.Users.Remove (U);
Dbcontext.savechanges ();
#endregion
#region The official recommended way to delete
Official recommended Removal method
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 Statements
Model1container dbcontext=new Model1container ();
int I=dbcontext.database.executesqlcommand (transactionalbehavior.ensuretransaction,
"Update users set username= ' John Doe ' where id=3");
#endregion
return View ();
}
}
}
2. Incidentally generated class I'm going to put it in here, too.
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>
This code has been generated from the template.
//
Manually changing this file may cause unexpected behavior in your application.
If you regenerate the code, the manual changes to this file are overwritten.
</auto-generated>
//------------------------------------------------------------------------------
Namespace Webapplication3.models
{
Using System;
Using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "ca2214:d Onotcalloverridablemethodsinconstructors ")]
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. I paste the configuration file here, in fact, can be generated according to the graphical interface operation, here also must know the principle, otherwise cannot change
<?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= "None"/>
<designerproperty name= "Uselegacyprovider" value= "False"/>
</DesignerInfoPropertySet>
</edmx:Options>
<!--Diagram content (shape and connector positions)-
<edmx:Diagrams>
</edmx:Diagrams>
</edmx:Designer>
</edmx:Edmx>
EF common Statements and SQL statements continue to be added in a simple follow-up