Entiy Framework Research-infrastructure layer

Source: Internet
Author: User

The infrastructure layer mainly includes three projects:

1. Data entities correspond to tables and views of data

There is a basic entity class, which is used to limit the wildcard object input of repository, and some methods such as hashcode are also overloaded to facilitate data entity comparison. There is also a class that aids in primary key generation, the Code is as follows:

1. entity class

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Chart.Workflow.Infrastructure.Data{    public class Entity    {        #region Members        int? _requestedHashCode;        string _Id;        #endregion        #region Properties        /// <summary>        /// Get the persisten object identifier        /// </summary>        public virtual string Id        {            get            {                return _Id;            }            protected set            {                _Id = value;            }        }        #endregion        #region Public Methods        /// <summary>        /// Check if this entity is transient, ie, without identity at this moment        /// </summary>        /// <returns>True if entity is transient, else false</returns>        public bool IsTransient()        {            return string.IsNullOrEmpty(this.Id);        }        /// <summary>        /// Generate identity for this entity        /// </summary>        public void GenerateNewIdentity()        {            if (IsTransient())                this.Id = IdentityGenerator.NewSequentialId();        }        /// <summary>        /// Change current identity for a new non transient identity        /// </summary>        /// <param name="identity">the new identity</param>        public void ChangeCurrentIdentity(string identity)        {            if (!string.IsNullOrEmpty(this.Id))                this.Id = identity;        }        #endregion        #region Overrides Methods        /// <summary>        /// <see cref="M:System.Object.Equals"/>        /// </summary>        /// <param name="obj"><see cref="M:System.Object.Equals"/></param>        /// <returns><see cref="M:System.Object.Equals"/></returns>        public override bool Equals(object obj)        {            if (obj == null || !(obj is Entity))                return false;            if (Object.ReferenceEquals(this, obj))                return true;            Entity item = (Entity)obj;            if (item.IsTransient() || this.IsTransient())                return false;            else                return item.Id == this.Id;        }        /// <summary>        /// <see cref="M:System.Object.GetHashCode"/>        /// </summary>        /// <returns><see cref="M:System.Object.GetHashCode"/></returns>        public override int GetHashCode()        {            if (!IsTransient())            {                if (!_requestedHashCode.HasValue)                    _requestedHashCode = this.Id.GetHashCode() ^ 31;                 // XOR for random distribution                (http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx)                return _requestedHashCode.Value;            }            else                return base.GetHashCode();        }        public static bool operator ==(Entity left, Entity right)        {            if (Object.Equals(left, null))                return (Object.Equals(right, null)) ? true : false;            else                return left.Equals(right);        }        public static bool operator !=(Entity left, Entity right)        {            return !(left == right);        }        #endregion    }}

2. identitygenerator class

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Chart.Workflow.Infrastructure.Data{    public static class IdentityGenerator    {        /// <summary>        /// This algorithm generates secuential strings across system boundaries, ideal for databases         /// </summary>        /// <returns></returns>        public static string NewSequentialId()        {            string resut = Guid.NewGuid().ToString().Replace("-", "");            return resut;        }        /// <summary>        /// This algorithm generates secuential strings across system boundaries, ideal for databases         /// </summary>        /// <returns></returns>        public static Guid NewSequentialGuid()        {            byte[] uid = Guid.NewGuid().ToByteArray();            byte[] binDate = BitConverter.GetBytes(DateTime.UtcNow.Ticks);            byte[] secuentialGuid = new byte[uid.Length];            secuentialGuid[0] = uid[0];            secuentialGuid[1] = uid[1];            secuentialGuid[2] = uid[2];            secuentialGuid[3] = uid[3];            secuentialGuid[4] = uid[4];            secuentialGuid[5] = uid[5];            secuentialGuid[6] = uid[6];            // set the first part of the 8th byte to '1100' so                 // later we'll be able to validate it was generated by us               secuentialGuid[7] = (byte)(0xc0 | (0xf & uid[7]));            // the last 8 bytes are sequential,                // it minimizes index fragmentation               // to a degree as long as there are not a large                // number of Secuential-Guids generated per millisecond              secuentialGuid[9] = binDate[0];            secuentialGuid[8] = binDate[1];            secuentialGuid[15] = binDate[2];            secuentialGuid[14] = binDate[3];            secuentialGuid[13] = binDate[4];            secuentialGuid[12] = binDate[5];            secuentialGuid[11] = binDate[6];            secuentialGuid[10] = binDate[7];            return new Guid(secuentialGuid);        }    }}

2. secondary aspect: it is mainly used for global features such as verification, logs, and resources;

The basic method is as follows:

Iii. Data context, mainly the implementation of basic data access operations

1. Use the iSQL interface for SQL statement query:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Chart.Workflow.Infrastructure.Context{    public interface ISql    {        IEnumerable<TEntity> ExecuteQuery<TEntity>(string sqlQuery, params object[] parameters);        int ExecuteCommand(string sqlCommand, params object[] parameters);    }}

2. iqueryunitofwork class. Simple data operations are as follows:

using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Chart.Workflow.Infrastructure.Context{    public interface IQueryUnitOfWork:IUnitOfWork,ISql    {        DbSet<TEntity> CreateSet<TEntity>() where TEntity : class;        void Attach<TEntity>(TEntity item) where TEntity : class;        void SetModified<TEntity>(TEntity item) where TEntity : class;        void ApplyCurrentValues<TEntity>(TEntity original, TEntity current) where TEntity : class;    }}

3. iunitofwork interface:

using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Chart.Workflow.Infrastructure.Context{    public interface IUnitOfWork : IDisposable    {        void Commit();        void CommitAndRefreshChanges();        void RollbackChanges();    }}

4. unitofwork class. The core data operations are as follows:

Using chart. workflow. infrastructure. data; using system. collections. generic; using system. data. entity; using system. data. entity. infrastructure; using system. data. entity. modelconfiguration. conventions; using system. LINQ; using system. text; using system. threading. tasks; namespace chart. workflow. infrastructure. context {public class unitofwork: dbcontext, iqueryunitofwork {idbset <student> _ students; Public idbset <student> students {get {If (_ students = NULL) _ students = base. set <student> (); Return _ students ;}} idbset <course> _ course; Public idbset <course> courses {get {If (_ course = NULL) _ course = base. set <course> (); Return _ course;} public unitofwork (): Base () {} public unitofwork (string connectionstring): Base (connectionstring) {}# region iqueryunitofwork members public dbset <tentity> createset <tentity> () Where tentity: Class {return base. set <tentity> ();} public void attach <tentity> (tentity item) Where tentity: Class {// attach and set as unchanged base. entry <tentity> (item ). state = system. data. entitystate. unchanged;} public void setmodified <tentity> (tentity item) Where tentity: Class {// This operation also attach item in object state manager base. entry <tentity> (item ). state = system. data. entitystate. modified;} public void applycurrentvalues <tentity> (tentity original, tentity current) Where tentity: Class {// if it is not attached, attach original and set current values base. entry <tentity> (original ). currentvalues. setvalues (current);} public void commit () {base. savechanges ();} public void commitandrefreshchanges () {bool savefailed = false; do {try {base. savechanges (); savefailed = false;} catch (dbupdateconcurrencyexception ex) {savefailed = true; Ex. entries. tolist (). foreach (Entry => {entry. originalvalues. setvalues (entry. getdatabasevalues () ;}}}while (savefailed);} public void rollbackchanges () {// set all entities in change tracker // As 'unchanged state' base. changetracker. entries (). tolist (). foreach (Entry => entry. state = system. data. entitystate. unchanged);} public ienumerable <tentity> executequery <tentity> (string sqlquery, Params object [] parameters) {If (parameters = NULL) {parameters = new object [0];} return base. database. sqlquery <tentity> (sqlquery, parameters);} public int executecommand (string sqlcommand, Params object [] parameters) {If (parameters = NULL) {parameters = new object [0];} return base. database. executesqlcommand (sqlcommand, parameters) ;}# endregion # region dbcontext overrides protected override void onmodelcreating (dbmodelbuilder modelbuilder) {// Remove unused conventions // onetomanycascadedeleteconvention modelbuilder. conventions. remove <pluralizingtablenameconvention> (); // inconsistent database tables and object types Use modelbuilder. entity <student> (). totable ("student"); modelbuilder. entity <course> (). totable ("Course"); // the configuration file modelbuilder. events. add (New studententitytypeconfiguration (); modelbuilder. events. add (New courseentitytypeconfiguration () ;}# endregion }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.