Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all 1698 articles
Browse latest View live

c# a field initializer cannot reference the non-static field method or property + unit of work

$
0
0

when i try to share one instance of unit of work i get this error compiler in mvc controller code

c# a field initializer cannot reference the non-static field method or property

how o fix this?

this my Business logic

BLLBase

public abstract class BLLBase
{
        private UniteOfWork _unitOfWork  ;
        public UniteOfWork UniteOfWork 
        {
            get 
            {
                return _unitOfWork ;
            }

            set {
                _unitOfWork = value;
            }
        }
}

the BLL classes

publicclassExpenseBLL :BLLBase
{// the rest of codepublicExpenseBll(UnitOfWork unitofwork){this.UniteOfWork = unitOfWork;
}}
publicclassInvoiceBLL :BLLBase
{// the rest of code
publicInvoiceBLL(UnitOfWork unitofwork)
{

this.UniteOfWork = unitOfWork;
}
}

a controller codes

UnitOfWork unitofWork = new UnitOfWork();

InvoiceBll invoiceBll = new InvoiceBll(unitofWork);
ExpenseBll expenseBll = new ExpenseBll(unitofWork);


Data type mismatch in criteria expression , Syntax error in UPDATE statement

$
0
0

hi guys

why in update link have this error  Syntax error in UPDATE statement. ?

why in delete link have this error  Data type mismatch in criteria expression. ?

    protected void textBAID_Click(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            string strSQL = null;

            string strConnection = ConfigurationManager.ConnectionStrings["AccessDADB"].ConnectionString;
            strSQL = "Update Dawabka_Basket SET ([Basket_Perm] = ?)  where BAID = '" + Request.QueryString["BAID"] + "'";

            //Call Open database - connect to the database

            OleDbConnection objConnection = new OleDbConnection(strConnection);
            OleDbCommand objCommand = new OleDbCommand(strSQL, objConnection);

            objConnection.Open();
            objCommand.Parameters.AddWithValue("@Basket_Perm", "1");
            objCommand.ExecuteNonQuery();
            objCommand = null;
            objConnection.Close();
            objConnection = null;

            lblSSuccess.Text = "به‌سه‌رکه‌وتوی یه‌که‌ی نیشته‌جێ بون زیاد کرا, چاوه‌روان به‌ بۆ ده‌رکه‌وتن له‌ لیستی یه‌که‌کان.";
            lblSSuccess.ForeColor = ColorTranslator.FromHtml("green");
        }
    }
    protected void textBAID_Click1(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            string strSQL = null;

            string strConnection = ConfigurationManager.ConnectionStrings["AccessDADB"].ConnectionString;
            strSQL = "DELETE FROM Dawabka_Basket where [BAID] ='" + Request.QueryString["BAID"] + "' ";

            //Call Open database - connect to the database

            OleDbConnection objConnection = new OleDbConnection(strConnection);
            OleDbCommand objCommand = new OleDbCommand(strSQL, objConnection);

            objConnection.Open();
            objCommand.ExecuteNonQuery();
            objCommand = null;
            objConnection.Close();
            objConnection = null;

            lblSSuccess.Text = "به‌سه‌رکه‌وتوی یه‌که‌ی نیشته‌جێ بون زیاد کرا, چاوه‌روان به‌ بۆ ده‌رکه‌وتن له‌ لیستی یه‌که‌کان.";
            lblSSuccess.ForeColor = ColorTranslator.FromHtml("green");
        }
    }
<asp:TemplateField HeaderText="Goren"><ItemTemplate><asp:LinkButton ID="textBAID" runat="server" CommandArgument='<%# Eval("BAID").ToString() %>' OnClick="textBAID_Click">update</asp:LinkButton><asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("BAID").ToString()  %>' OnClick="textBAID_Click1">delet</asp:LinkButton></ItemTemplate></asp:TemplateField>

Different behaviour between bridging and standalone model/class

$
0
0

We are trying to streamline our automatic updating fields for DateCreated, CreatedBy, LastDateModified, LastModifiedBy, DateDeleted and DeletedBy and worked OK by adding routine OnBeforeSaving in the ApplicationDBContext.cs and we also do the SOFT-DELETE for retaining the records (flagged as IsDeleted approach instead) when we deleted:

ApplicationDBContext.cs -

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using AthlosifyWebArchery.Models;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;

namespace AthlosifyWebArchery.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, 
                                            IdentityUserClaim<string>,
                                            ApplicationUserRole, IdentityUserLogin<string>,
                                            IdentityRoleClaim<string>, IdentityUserToken<string>>
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
                IHttpContextAccessor httpContextAccessor
                )
        : base(options)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public DbSet<AthlosifyWebArchery.Models.TournamentBatchItem> TournamentBatchItem { get; set; }
        public DbSet<AthlosifyWebArchery.Models.TournamentBatch> TournamentBatch { get; set; }

        public virtual DbSet<AthlosifyWebArchery.Models.Host> Host { get; set; }

        public DbSet<AthlosifyWebArchery.Models.HostApplicationUser> HostApplicationUser { get; set; }

        public virtual DbSet<AthlosifyWebArchery.Models.Club> Club { get; set; }

        public DbSet<AthlosifyWebArchery.Models.ClubApplicationUser> ClubApplicationUser { get; set; }


        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            foreach (var entityType in builder.Model.GetEntityTypes())
            {
                // 1. Add the IsDeleted property
                entityType.GetOrAddProperty("IsDeleted", typeof(bool));

                // 2. Create the query filter

                var parameter = Expression.Parameter(entityType.ClrType);

                // EF.Property<bool>(post, "IsDeleted")
                var propertyMethodInfo = typeof(EF).GetMethod("Property").MakeGenericMethod(typeof(bool));
                var isDeletedProperty = Expression.Call(propertyMethodInfo, parameter, Expression.Constant("IsDeleted"));

                // EF.Property<bool>(post, "IsDeleted") == false
                BinaryExpression compareExpression = Expression.MakeBinary(ExpressionType.Equal, isDeletedProperty, Expression.Constant(false));

                // post => EF.Property<bool>(post, "IsDeleted") == false
                var lambda = Expression.Lambda(compareExpression, parameter);

                builder.Entity(entityType.ClrType).HasQueryFilter(lambda);
            }

            // Many to Many relationship - HostApplicationUser
            builder.Entity<HostApplicationUser>()
                    .HasKey(bc => new { bc.HostID, bc.Id });

            builder.Entity<HostApplicationUser>()
                    .HasOne(bc => bc.Host)
                    .WithMany(b => b.HostApplicationUsers)
                    .HasForeignKey(bc => bc.HostID);

            builder.Entity<HostApplicationUser>()
                    .HasOne(bc => bc.ApplicationUser)
                    .WithMany(c => c.HostApplicationUsers)
                    .HasForeignKey(bc => bc.Id);


            // Many to Many relationship - ClubApplicationUser
            builder.Entity<ClubApplicationUser>()
                    .HasKey(bc => new { bc.ClubID, bc.Id });

            builder.Entity<ClubApplicationUser>()
                    .HasOne(bc => bc.Club)
                    .WithMany(b => b.ClubApplicationUsers)
                    .HasForeignKey(bc => bc.ClubID);

            builder.Entity<ClubApplicationUser>()
                    .HasOne(bc => bc.ApplicationUser)
                    .WithMany(c => c.ClubApplicationUsers)
                    .HasForeignKey(bc => bc.Id);

            // Many to Many relationship - ApplicationUserRole
            builder.Entity<ApplicationUserRole>(userRole =>
            {
                userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

                userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.ApplicationUserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
            });
        }

        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            OnBeforeSaving();
            return base.SaveChanges(acceptAllChangesOnSuccess);
        }

        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
        {
            OnBeforeSaving();
            return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }

        private void OnBeforeSaving()
        {
            if (_httpContextAccessor.HttpContext != null)
            {
                var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
                var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

                // Added
                var added = ChangeTracker.Entries().Where(v => v.State == EntityState.Added && 
                                typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();

                added.ForEach(entry =>
                {
                    ((IBaseEntity)entry.Entity).DateCreated = DateTime.UtcNow;
                    ((IBaseEntity)entry.Entity).CreatedBy = userId;
                    ((IBaseEntity)entry.Entity).LastDateModified = DateTime.UtcNow;
                    ((IBaseEntity)entry.Entity).LastModifiedBy = userId;
                });

                // Modified
                var modified = ChangeTracker.Entries().Where(v => v.State == EntityState.Modified &&
                                typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();

                modified.ForEach(entry =>
                {
                    ((IBaseEntity)entry.Entity).LastDateModified = DateTime.UtcNow;
                    ((IBaseEntity)entry.Entity).LastModifiedBy = userId;
                });

                // Deleted
                var deleted = ChangeTracker.Entries().Where(v => v.State == EntityState.Deleted &&
                                typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();

                deleted.ForEach(entry =>
                {
                    ((IBaseEntity)entry.Entity).DateDeleted = DateTime.UtcNow;
                    ((IBaseEntity)entry.Entity).DeletedBy = userId;
                });

                foreach (var entry in ChangeTracker.Entries()
                                        .Where(e => e.State == EntityState.Deleted &&
                                        e.Metadata.GetProperties().Any(x => x.Name == "IsDeleted")))
                {
                    switch (entry.State)
                    {
                        case EntityState.Added:
                            entry.CurrentValues["IsDeleted"] = false;
                            break;
                        case EntityState.Deleted:
                            entry.State = EntityState.Modified;
                            entry.CurrentValues["IsDeleted"] = true;
                            break;
                    }
                }
            }
            else
            {
                // DbInitializer kicks in
            }
        }
    }
}

Worked OK with standalone model/class ie. Club, Host, ApplicationUser ** BUT not bridging model/class ie. **ClubApplicationUser and HostApplicationUser

So we have to do manually on this (AssignClub.cshtml.cs for instance) by adding manually for creating/deleting as you can see below:

// Removed the current one
                    var clubApplicationUserToRemove = await _context.ClubApplicationUser
                                                                .FirstOrDefaultAsync(m => m.Id == id.ToString()&& m.ClubID == AssignClubUser.OriginalClubID);

                    clubApplicationUserToRemove.DateDeleted = DateTime.UtcNow;
                    clubApplicationUserToRemove.DeletedBy = userID;
                    _context.ClubApplicationUser.Remove(clubApplicationUserToRemove);

... the deleted.Count() below returning 0 ... and the same with creating etc:

// Deleted
                var deleted = ChangeTracker.Entries().Where(v => v.State == EntityState.Deleted &&
                                typeof(IBaseEntity).IsAssignableFrom(v.Entity.GetType())).ToList();

                deleted.ForEach(entry =>
                {
                    ((IBaseEntity)entry.Entity).DateDeleted = DateTime.UtcNow;
                    ((IBaseEntity)entry.Entity).DeletedBy = userId;

AssignClub.cshtml.cs -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AthlosifyWebArchery.Data;
using AthlosifyWebArchery.Models;
using AthlosifyWebArchery.Pages.Administrators.TournamentBatches;
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using static AthlosifyWebArchery.Pages.Administrators.Users.AssignClubUserModel;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace AthlosifyWebArchery.Pages.Administrators.Users
{
    //public class AssignClubUserModel : ClubNamePageModel
    public class AssignClubUserModel : UserViewPageModel
    {
        private readonly AthlosifyWebArchery.Data.ApplicationDbContext _context;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public AssignClubUserModel(AthlosifyWebArchery.Data.ApplicationDbContext context,
                                        IHttpContextAccessor httpContextAccessor
                                    )
        {
            _context = context;
            _httpContextAccessor = httpContextAccessor;
        }

        public class AssignClubUserViewModel<ApplicationUser>
        {
            public string Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string UserName { get; set; }
            public Guid ClubID { get; set; }
            public Guid OriginalClubID { get; set; }
            public byte[] RowVersion { get; set; }
        }

        [BindProperty]
        public AssignClubUserViewModel<ApplicationUser> AssignClubUser { get; set; }

        //public SelectList ClubNameSL { get; set; }

        public async Task<IActionResult> OnGetAsync(Guid? id)
        {
            if (id == null)
                return NotFound();

            AssignClubUser = await _context.Users
                            .Include(u => u.ClubApplicationUsers)
                            .Where(t => t.Id == id.ToString())
                            .Select(t => new AssignClubUserViewModel<ApplicationUser>
                            {
                                Id = t.Id,
                                FirstName = t.FirstName,
                                LastName = t.LastName,
                                UserName = t.UserName,
                                ClubID = t.ClubApplicationUsers.ElementAt(0).ClubID,
                                OriginalClubID = t.ClubApplicationUsers.ElementAt(0).ClubID,
                                RowVersion =  t.ClubApplicationUsers.ElementAt(0).RowVersion
                            }).SingleAsync();

            if (AssignClubUser == null)
                return NotFound();


            // Use strongly typed data rather than ViewData.
            //ClubNameSL = new SelectList(_context.Club, "ClubID", "Name");

            PopulateClubsDropDownList(_context, AssignClubUser.ClubID);

            return Page();
        }

        public async Task<IActionResult> OnPostAsync(Guid id)
        {
            if (!ModelState.IsValid)
                return Page();

            // 1st approach: 
            // Modify the bridge model directly

            /*var clubApplicationUserToUpdate = await _context.ClubApplicationUser
                                                        .FirstOrDefaultAsync(m => m.Id == id.ToString() && m.ClubID == AssignClubUser.OriginalClubID);

            if (clubApplicationUserToUpdate == null) 
                return await HandleDeletedUser();

            _context.Entry(clubApplicationUserToUpdate)
                .Property("RowVersion").OriginalValue = AssignClubUser.RowVersion;

            // This slightly tweek for this particular 
            // As the modified Change Track is not triggered

            //_context.Entry(clubApplicationUserToUpdate)
            //    .Property("LastDateModified").CurrentValue = DateTime.UtcNow;

            //_context.Entry(clubApplicationUserToUpdate)
            //    .Property("LastModifiedBy").CurrentValue = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (await TryUpdateModelAsync<ClubApplicationUser>(
                clubApplicationUserToUpdate,"AssignClubUser",
                s => s.Id, s => s.ClubID))
            {
                try
                {
                    await _context.SaveChangesAsync();
                    return RedirectToPage("./Index");
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues = (ClubApplicationUser)exceptionEntry.Entity;
                    var databaseEntry = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty, "Unable to save. " +"The club application user was deleted by another user.");
                        return Page();
                    }

                    var dbValues = (ClubApplicationUser)databaseEntry.ToObject();
                    await setDbErrorMessage(dbValues, clientValues, _context);

                    AssignClubUser.RowVersion = (byte[])dbValues.RowVersion;

                    ModelState.Remove("User.RowVersion");
                }
            }
            */

            // 2nd approach: 
            // Soft -Delete and Add 
            // Did the soft-deleting and managed to add a new one BUT then die the roll back (adding the old one)
            // Result: Violation of PRIMARY KEY constraint 'PK_ClubApplicationUser'. 
            // Cannot insert duplicate key in object 
            // Due to duplicate key

            /*var clubApplicatonUserToRemove = await _context.ClubApplicationUser
                                            .FirstOrDefaultAsync(m => m.Id == id.ToString());
            ClubApplicationUser clubApplicatonUserToAdd = new ClubApplicationUser();
            clubApplicatonUserToAdd.Id = id.ToString();
            clubApplicatonUserToAdd.ClubID = AssignClubUser.SelectedClubID;


            //_context.Entry(clubApplicatonUserToRemove)
            //    .Property("RowVersion").OriginalValue = User.RowVersion;

            if (clubApplicatonUserToRemove != null)
            {
                _context.ClubApplicationUser.Remove(clubApplicatonUserToRemove);
                await _context.SaveChangesAsync();clubApplicationUserDeleted
                _context.ClubApplicationUser.Add(clubApplicatonUserToAdd);
                await _context.SaveChangesAsync();
            }*/

            //delete all club memberships and add new one

            //var clubApplicationUserDeleted = await _context.ClubApplicationUser
            //                                    .FirstOrDefaultAsync(m => m.Id == id.ToString()
            //                                        && m.ClubID == AssignClubUser.ClubID && m.IsDeleted == );

            var userID = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (AssignClubUser.ClubID != AssignClubUser.OriginalClubID)
            { 
                var deletedClubApplicationUsers = _context.ClubApplicationUser.IgnoreQueryFilters()
                                                    .Where(post => post.Id == id.ToString()&& post.ClubID == AssignClubUser.ClubID && EF.Property<bool>(post, "IsDeleted") == true);

                if (deletedClubApplicationUsers.Count() > 0)
                {
                    // Undo the deleted one
                    foreach (var deletedClubApplicationUser in deletedClubApplicationUsers)
                    {
                        var postEntry = _context.ChangeTracker.Entries<ClubApplicationUser>().First(entry => entry.Entity == deletedClubApplicationUser);
                        postEntry.Property("IsDeleted").CurrentValue = false;
                        postEntry.Property("LastDateModified").CurrentValue = DateTime.UtcNow;
                        postEntry.Property("LastModifiedBy").CurrentValue = userID;
                        postEntry.Property("DateDeleted").CurrentValue = null;
                        postEntry.Property("DeletedBy").CurrentValue = null;
                    }

                    // Removed the current one
                    var clubApplicationUserToRemove = await _context.ClubApplicationUser
                                                                .FirstOrDefaultAsync(m => m.Id == id.ToString()&& m.ClubID == AssignClubUser.OriginalClubID);

                    clubApplicationUserToRemove.DateDeleted = DateTime.UtcNow;
                    clubApplicationUserToRemove.DeletedBy = userID;
                    _context.ClubApplicationUser.Remove(clubApplicationUserToRemove);

                    try
                    {
                        await _context.SaveChangesAsync();
                        return RedirectToPage("./Index");
                    }
                    catch
                    {
                        PopulateClubsDropDownList(_context, AssignClubUser.ClubID);
                        return Page();
                    }
                }
                else
                {
                    // Removed the current one
                    var clubApplicationUserToRemove = await _context.ClubApplicationUser
                                                            .FirstOrDefaultAsync(m => m.Id == id.ToString()&& m.ClubID == AssignClubUser.OriginalClubID);
                    clubApplicationUserToRemove.DateDeleted = DateTime.UtcNow;
                    clubApplicationUserToRemove.DeletedBy = userID;
                    _context.ClubApplicationUser.Remove(clubApplicationUserToRemove);

                    try
                    {
                        _context.Entry(clubApplicationUserToRemove).State = EntityState.Deleted;
                        await _context.SaveChangesAsync();
                    }
                    catch
                    {
                        PopulateClubsDropDownList(_context, AssignClubUser.ClubID);
                        return Page();
                    }

                    // Added the new one
                    var newClubApplicationUser = new ClubApplicationUser()
                    {
                        Id = id.ToString(),
                        ClubID = AssignClubUser.ClubID,
                        DateCreated = DateTime.UtcNow,
                        CreatedBy = userID,
                        LastDateModified = DateTime.UtcNow,
                        LastModifiedBy = userID
                    };
                    _context.ClubApplicationUser.Add(newClubApplicationUser);

                    try
                    {
                        _context.Entry(newClubApplicationUser).State = EntityState.Added;
                        await _context.SaveChangesAsync();
                        return RedirectToPage("./Index");
                    }
                    catch
                    {
                        PopulateClubsDropDownList(_context, AssignClubUser.ClubID);
                        return Page();
                    }
                }
            }

            return RedirectToPage("./Index");
        }

        private async Task<IActionResult> HandleDeletedUser()
        {
        ClubApplicationUser deletedClubApplicationUser = new ClubApplicationUser();
        ModelState.AddModelError(string.Empty,"Unable to save. The club was deleted by another user.");
        return Page();
        }

        private async Task setDbErrorMessage(ClubApplicationUser dbValues,
            ClubApplicationUser clientValues, ApplicationDbContext context)
        {
        ModelState.AddModelError(string.Empty,
            "The record you attempted to edit "+ "was modified by another user after you. The "+ "edit operation was canceled and the current values in the database "+ "have been displayed. If you still want to edit this record, click "+ "the Save button again.");
        }

    }
}

Any ideas? The current solution is working OK BUT it just has extra routines to add these DateCreated, CreatedBy, LastDateModified, LastModifiedBy, DateDeleted and DeletedBy manually for this bridging model/class.

Environment:

  • .NET Core 2.2
  • SQL Server

Finding 1:

We even add this before the saving and it didn't trigger the automatic ChangeTracker.Entries():

_context.Entry(newClubApplicationUser).State = EntityState.Deleted;
await _context.SaveChangesAsync();

LINQ lambda syntax for counting number of sequence

$
0
0

Hello all,

I got table Student records in database as follows:

ExamDate         Test           Result
01/21/2016         Math           Pass
06/02/2016         Art               Pass
05/31/2017         Math           Fail
06/28/2017         Art              Pass
07/03/2017         Math          Pass
07/19/2017         Art              Fail
08/01/2017         Math          Fail
09/13/2017         Art              Fail
09/15/2017         Math          Fail
10/01/2017         Art              Fail
10/10/2017         Math          Pass
10/11/2017         Art             Fail

....

In above sample data, there are 4 sequential fails in a row. Anyone can help me to write LINQ lambda to counting how many sequential fails in a row based on exam date?

Thanks in advance.

Linq result fails when checking for null value for column.

$
0
0

Why this Linq query fails?

string blogCategoryId=null;
var r1 = context.Blog.Where(x => (blogCategoryId != null && x.CategoryId == blogCategoryId)).ToList();

I want this query should return all blogs without where condition since blogCategoryId is null. 

But this query return 0 records stating the where condition x.CategoryId == blogCategoryId has been applied?

Why it is so?

Error In Add Record

$
0
0

Hi,
When I Add Record In Asp.net Core Mvc , the record is added but after that it's show this error.
what's problem?

City

 public City()
        {

        }
        [Key]
        public int City_ID { get; set; }
        [DisplayName("نام شهر")]
        [Required(ErrorMessage = "لطفا {0} را وارد نمایید")]
        [MaxLength(50)]
        public string CityName { get; set; }
        [DisplayName("کد شهر")]
        [Column(TypeName = "varchar(10)")]
        public string CityCode { get; set; }
        [DisplayName("وضعیت")]
        public bool IsActive { get; set; }
        [DisplayName("استان")]
        public virtual State State { get; set; }
        [DisplayName("استان")]

        public int State_ID { get; set; }

        public virtual IEnumerable<CustomerAddress> CustomerAddresses { get; set; }

State

   [Key]
        public int State_ID { get; set; }
        [DisplayName("نام استان")]
        [Required(ErrorMessage = "لطفا {0} را وارد نمایید")]
        [MaxLength(50)]
        public string StateName { get; set; }
        [DisplayName("کد استان")]
        [Column(TypeName = "varchar(10)")]
        public string StateCode { get; set; }
        [DisplayName("وضعیت")]
        public bool IsActive { get; set; }
        [DisplayName("کشور")]
        [ForeignKey("Country")]
        public int CountryId { get; set; }

        public virtual Country Country { get; set; }
        public virtual List<City> Cities { get; set; }
        public virtual IEnumerable<CustomerAddress> CustomerAddresses { get; set; }




Is entity framework a must?

$
0
0

Hi,

I am a long time desktop app programmer with Delphi and MySQL.

I like them both and I like SQL.

However, I will be fully honest, I hate entity framework. It is neither SQL nor something else. It is just confusing.

Could you tell me who the haven created this framework and why?

Believe me, if I weren't afraid of SQL injection and other kinds of hack or something I would use ADO net with SQL.

Any help would be appreciated.

How to use PLINQ AsParallel when querying multiple object with multiple joins

$
0
0

see this LINQ query. please tell me how to use PLINQ here in my below query. if possible please give me a another version of same code where PLINQ will be used. thanks

var QCViewAllHistValue = (from viewalllst in QCViewAllBrokerList
join frmlst in customformulaList
on new
{
val = String.IsNullOrEmpty(viewalllst.ViewAllSection) ? "" : viewalllst.ViewAllSection.Trim().ToUpper(),
val1 = String.IsNullOrEmpty(viewalllst.ViewAllLineItem) ? "" : viewalllst.ViewAllLineItem.Trim().ToUpper(),
val2 = String.IsNullOrEmpty(viewalllst.ViewAllPeriod) ? "" : viewalllst.ViewAllPeriod.Replace("A", "").Replace("E", "").Trim().ToUpper(),
val3 = String.IsNullOrEmpty(viewalllst.ViewAllBroker) ? "" : viewalllst.ViewAllBroker.Trim().ToUpper()
}

equals new
{
val = String.IsNullOrEmpty(frmlst.Section) ? "" : frmlst.Section.Trim().ToUpper(),
val1 = String.IsNullOrEmpty(frmlst.Li) ? "" : frmlst.Li.Trim().ToUpper(),
val2 = String.IsNullOrEmpty(frmlst.Period) ? "" : frmlst.Period.Replace("A", "").Replace("E", "").Trim().ToUpper(),
val3 = String.IsNullOrEmpty(frmlst.Broker) ? "" : frmlst.Broker.Trim().ToUpper()

}
into tempJoin
from leftJoin in tempJoin.DefaultIfEmpty()
where viewalllst.Wtg == "1"
select new QCHelper()
{
Broker = viewalllst.ViewAllBroker == null ? string.Empty : viewalllst.ViewAllBroker,
Section = viewalllst.ViewAllSection == null ? string.Empty : viewalllst.ViewAllSection,
Li = viewalllst.ViewAllLineItem == null ? string.Empty : viewalllst.ViewAllLineItem,
Period = viewalllst.ViewAllPeriod == null ? string.Empty : viewalllst.ViewAllPeriod,
CrossCalc1Q = leftJoin == null ? string.Empty : leftJoin.CrossCalc1Q,
CrossCalc2Q = leftJoin == null ? string.Empty : leftJoin.CrossCalc2Q,
CrossCalc3Q = leftJoin == null ? string.Empty : leftJoin.CrossCalc3Q,
CrossCalc4Q = leftJoin == null ? string.Empty : leftJoin.CrossCalc4Q,
CrossCalcFY = leftJoin == null ? string.Empty : leftJoin.CrossCalcFY,
Value = viewalllst.Value == null ? string.Empty : viewalllst.Value,
QCFormula = leftJoin == null ? string.Empty : leftJoin.QCFormula,
CustomFormula = leftJoin == null ? string.Empty : leftJoin.CustomFormula,
Historical = leftJoin == null ? string.Empty : String.IsNullOrEmpty(leftJoin.Historical) ? "" : leftJoin.Historical,
DeriveCrossCalc = leftJoin == null ? string.Empty : leftJoin.DeriveCrossCalc
}).ToList<QCHelper>();

few more questions 

what AsParallel().AsOrdered() does ?

when to use AsParallel().WithExecutionMode ?

what is difference between AsOrdered & WithExecutionMode ?

thanks


Replace Factory with Autofac Module for Unit of Work

$
0
0

Summary of the problem I am having:

I am fairly new to coding and I am in the process of learning dependency injection using Autofac.  With past projects (not using Autofac), I have created a Factory to determine which objects get returned based on the value of the RepositoryType key set in the Web.config file.  So for example, if  the RepositoryType value is set to ADO, then I would want it (the factory) to return the Unit Of Work for ADO and register all the repositories, interfaces, unit of work, context in my DataAccessModule.  If the RepositoryType value is changed to DAPPER, then only my repositories, interfaces, unit of work, context would be registered and returned for DAPPER.  I'm just stuck on how to wire everything up via Autofac without implementing a Factory class for my unit of work and context classes. 

I also don't know how to use a ConfigurationProvider class (if I wanted to access the RepostioryType property) from my ConfigurationProviderModule in my DataAccessModule.  Are we allowed to resolve in another Module or is that frowned upon?

Any help or guidance you can provide on this topic would be greatly appreciated

My code:

<appSettings><add key="RepositoryType" value="ADO" /></appSettings>

IConfigurationProvider

public interface IConfigurationProvider
    {
        string RepositoryType { get; }

        IDbConnection CreateConnection();
    }

ConfigurationProvider

This class will hold the configuration information.  It has a CreateConnection method to open a connection - this gets called from my DvdContextADO

public class ConfigurationProvider : IConfigurationProvider
    {
        private readonly DbProviderFactory _provider;
        private readonly string _connectionName;
        private readonly string _connectionString;
        private readonly string _providerName;
        public string RepositoryType { get; private set; }

        public ConfigurationProvider(string connectionName, string connectionString, string providerName, string repositoryType)
        {
            _connectionName = connectionName ?? throw new ArgumentNullException("connectionName");
            _connectionString = connectionString ?? throw new ArgumentNullException("connectionString");
            _providerName = providerName ?? throw new ArgumentNullException("providerName");
            RepositoryType = repositoryType ?? throw new ArgumentNullException("repositoryType");
            _provider = DbProviderFactories.GetFactory(_providerName);
        }

        public IDbConnection CreateConnection()
        {
            var connection = _provider.CreateConnection();

            if (connection == null) throw new ConfigurationErrorsException($"Failed to create a connection using the connection string named '{_connectionName}' in web.config.");

            connection.ConnectionString = _connectionString;

            connection.Open();

            return connection;
        }
    }

ConfigurationModule

This module is responsible for registering the ConfigurationProvider class.  It reads the connection string information withinWeb.config

public class ConfigurationModule : Module
    {
        public string ConnectionName { get; set; }
        public string AppSettingKey { get; set; }

        protected override void Load(ContainerBuilder builder)
        {
            var connection = ConfigurationManager.ConnectionStrings[ConnectionName];

            if (connection == null) throw new ConfigurationErrorsException($"Failed to find connection string named '{ConnectionName}' in web.config.");

            builder.Register(c => new ConfigurationProvider(

                connectionName: ConfigurationManager.ConnectionStrings[ConnectionName].Name,
                connectionString: ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString,
                providerName: ConfigurationManager.ConnectionStrings[ConnectionName].ProviderName,
                repositoryType: ConfigurationManager.AppSettings[AppSettingKey]

                ))
                .As<IConfigurationProvider>()
                .SingleInstance();

            base.Load(builder);
        }
        
    }

DvdContextADO

Uses the ConfigurationProvider class

public class DvdContextADO
    {
        private readonly IDbConnection _connection;

        public DvdContextADO(IConfigurationProvider configurationProvider)
        {
            _connection = configurationProvider.CreateConnection();
            Transaction = _connection.BeginTransaction();
        }

        public IDbTransaction Transaction { get; private set; }

        public IDbCommand CreateCommand()
        {
            var cmd = _connection.CreateCommand();
            
            cmd.Transaction = Transaction;

            return cmd;
        }
    }

UnitOfWorkADO

Unit of Work specific to ADO

public class UnitOfWorkADO : IUnitOfWork
    {
        private readonly DvdContextADO _context;
        private IDbTransaction _transaction;

        private IDvdRepository _dvd;
        private IDvdDirectorRepository _dvdDirector;
        private IRatingRepository _rating;
        private IDirectorRepository _director;

        public UnitOfWorkADO(DvdContextADO context)
        {
            _context = context;
            _transaction = context.Transaction;
        }

        public IDirectorRepository Director
        {
            get
            {
                return _director ?? (_director = new DirectorRepositoryADO(_context));
            }
        }

        public IDvdDirectorRepository DvdDirector
        {
            get
            {
                return _dvdDirector ?? (_dvdDirector = new DvdDirectorRepositoryADO(_context));
            }
        }

        public IDvdRepository Dvd
        {
            get
            {
                return _dvd ?? (_dvd = new DvdRepositoryADO(_context));
            }
        }

        public IRatingRepository Rating
        {
            get
            {
                return _rating ?? (_rating = new RatingRepositoryADO(_context));
            }
        }

        public void Complete()
        {
            try
            {
                if (_transaction == null)
                {
                    return;
                }
                else
                {
                    _transaction.Commit();
                    _transaction = null;
                }

            }
            catch (Exception ex)
            {
                _transaction.Rollback();
                throw ex;
            }
        }

        public void Dispose()
        {
            if (_transaction != null)
            {
                _transaction.Dispose();
                _transaction = null;
            }
        }
    }

DataAccessModule

This is where I am stuck.  As you can see by the mess below, I am a bit lost, to say the least.  Any help you could provide would be greatly appreciated.

public class DataAccessModule : Module
    {
        private readonly IConfigurationProvider _configurationProvider;

        public string AppSettingsKey { get; set; }

        public DataAccessModule(IConfigurationProvider configurationProvider)
        {
            _configurationProvider = configurationProvider;
        }

        protected override void Load(ContainerBuilder builder)
        {
            var context = new DvdContextADO(_configurationProvider);

            builder.Register(c => new UnitOfWorkADO(context)).
                             As<IUnitOfWork>().InstancePerLifetimeScope();


            
            //var repositoryType = ConfigurationManager.AppSettings["RepositoryType"];

            //switch (repositoryType)
            //{
            //    case "ADO":
            //        builder.RegisterType<DvdContextADO>().AsSelf();
            //        builder.RegisterType<UnitOfWorkADO>().As<IUnitOfWork>().InstancePerLifetimeScope();
            //        builder.RegisterType<DirectorRepositoryADO>().As<IDirectorRepository>().InstancePerLifetimeScope();
            //        builder.RegisterType<DvdDirectorRepositoryADO>().As<IDvdDirectorRepository>().InstancePerLifetimeScope();
            //        builder.RegisterType<DvdRepositoryADO>().As<IDvdRepository>().InstancePerLifetimeScope();
            //        builder.RegisterType<RatingRepositoryADO>().As<IRatingRepository>().InstancePerLifetimeScope();
            //        break;
            //    default:
            //        throw new Exception("Could not find valid RepositoryType configuration value");
            //}


        }
    }

Insert a data without using insert command

$
0
0
Can I insert a data into my table without using insert command in asp.net project.

EF Core - Why can't we use class fields instead of properties in C# table definition?

$
0
0

Hello all!

I have the Book table class with property:  public DateTime PublishedOn { get; set; }

When I'm reading from property it seems good correct date value.

But when I'm changing it to public DateTime PublishedOn; and read again in string interpolation I've got 1-1-0001 0:00:00 value.

What's going wrong and where I can use field and when I can use property with one accessor? I haven't found this info.

If I'm using  public DateTime PublishedOn = DateTime.Now; then I'll get today date. 

Book class definition:

public class Book
{
public int BookId { get; set; }
public DateTime PublishedOn = DateTime.Now;

}

Reading code:

public static void Read()
{
using (var db = new ApDbContext())
{
foreach (var book in db.Books)
{
Console.WriteLine(" Published on " +
$"{book.PublishedOn}");
}
}
}

Thank you.

How can I create a group by in linq with one column?

$
0
0

Hi

I have the linq:

var noticesGrouped = notices.GroupBy(n => n.Name).Select(group=>new{NoticeName=group.Key,Count=group.Count()});
I would like to count by a specific column such as "writer"

The linq that I need is such as:

select Name as NoticeName,count(writer) from notices group by Name

Get only date value

$
0
0
 SqlDataAdapter da = new SqlDataAdapter("select no,CONVERT(DATE,CDate) as Create_Date,Itime,OTime from App where ID=@ID", sql_con);

                    da.SelectCommand.Parameters.Add("@ID", SqlDbType.VarChar);
                    da.SelectCommand.Parameters["@ID"].Value = ID;

                    da.Fill(ds);


I want to get only the date value from this datetime "2018-11-05 00:00:00.000". When I am running the sql statement("select no,CONVERT(DATE,CDate) as Create_Date,Itime,OTime from App") in sql server it returns the only date value but in dataset it is displaying the whole date and time value.

LINQ lambda to filter the value from the List or Dictionary

$
0
0

Hello,

I am trying to write LINQ for filter the records based on values in the List or Dictionay

List<int> failStudentIds = new List<int>();
failStudentIds.Add(x.StudentId)

or

Dictionary<int, string> failStudentIds = new Dictionary<int, string>
failStudentIds.Add(x.StudentId, 0)

I would like to get LINQ for filter the value from failStudentIds as belows:

var query = students.Where(x => x.StudentId == ?)

Thanks in advance.

How can I assign Linq.Data.Table(of ) to a variable, where is a string

$
0
0

Is there a way to a assign a DatabaseContext Table to a variable using variable in place of type?
I know I can use
Dim MyTable as Linq.Data.Table(of Products)

Say if I have 3 tables with different names but all 3 have same structure (fields & types), and would like to make a function to query any table based on function parameter

Private Function QryTable(byval WhatTable as string) as List(of string)
Dim MyList as List(of String) = Nothing
Dim MyDB as new MyDBDatabaseContext
Dim MyTable as Linq.Data.Table(WhatTable) <--- How can I use function parameter here
Select Case WhatTable
  Case "table1"
    MyTable = MyDB.ProductsA
  Case "table2"
   MyTable = MyDB.ProductsB
  Case "table3"
   MyTable = MyDB.ProductsC
Case Else
Return MyList
End Select

MyList = (From p in MyTable select p.Description).ToList
Return MyList
End Function


How can I built an Entityframework which can work both MySQL and MsSQL dbs

$
0
0

Hi all,

I have MySQL db behind my .net core app and have plan to convert it to MsSQL in future. (detailed story but I have to).

And because of the beauty of the ORM I thought it would be magically easy.

But it is not. Because mysql.data uses sql for data transfer unlike entityframework.

look at the symplifed code I use to update data to my MySQL db. Am I doing something wrong? Should I install entityframework package for MySQL and try to use it (which is shown in nowhere!).

Any help would be appreciated.

  using (MySqlConnection conn = GetConnection())
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand("Update evraklar set " +"gonderen=@gonderen, " +"ebysno=@ebysno, " +"gonderen_no=@gonderen_no, " +"gondermetarihi=@gondermetarihi, " +                        " where evraklar_id=@evraklar_id ", conn);
                    cmd.Parameters.AddWithValue("@evraklar_id", id);
                    cmd.Parameters.AddWithValue("@gonderen",gonderen );
                    cmd.Parameters.AddWithValue("@ebysno", ebysno);
                    cmd.Parameters.AddWithValue("@gonderen_no", gonderen_no);
                    cmd.ExecuteNonQueryAsync();
                }

"An attempt was made to use the context while it is being configured" error

$
0
0

Hi All,

Obviously I have problem with my DBcontext setup because when I try to get data from 2 different table with 2 different context via 2 in succession jquery $.get method I got the error

System.InvalidOperationException
HResult=0x80131509
Message=An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread-safe.
Source=Microsoft.EntityFrameworkCore

Connection settings

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySQL("server=localhost;port=3306;user=root;password=xxx;database=evraka");                
            }
        }

startup

 services.Add(new ServiceDescriptor(typeof(EvrakaContext), new EvrakaContext(Configuration.GetConnectionString("EvrakaContext"))));

usage 

neither of these ways  are working 

      public List<string> TumIllerListesi()
        {
            EvrakaContext context = HttpContext.RequestServices.GetService(typeof(EvrakaContext)) as EvrakaContext;
            return context.Set<Iller>().Select(u => u.Il).ToList();
        }
    private readonly EvrakaContext _context;

        public NumuneKabulController(EvrakaContext context)
        {
            _context = context;
        }

public  IList<string> GonderenListesiYukle()
        {
            return  _context.Set<Gonderenler>().Select(u => u.Gonderenmakam).ToList();
            //Debugger.Break();         


        }

Ef Scheme for multi language translations.

$
0
0

I'm building simple web application where article can have multi language translation below is my database scheme in entity framework 

    public class Book
    {
        [Key]
        public int Id { get; set; }
        public int Number { get; set; }
        public string Content { get; set; }
        public virtual ICollection<Translation> Translations { get; set; }
    }
    public class Translation
    {
        [Key]
        public int Id { get; set; }
        public string Content { get; set; }
        public int LanguageId { get; set; }
        [ForeignKey("LanguageId")]
        public Language Language { get; set; }
        public int BookId { get; set; }
        [ForeignKey("BookId")]
        public Book Kitab { get; set; }
    }
    public class Language
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string KeyCode { get; set; }
    }

I'm not sure if this is the right database scheme model, I'm plan to add search (in this case dropdown list) that has feature to choose language, for example if i choose english language it will show translation in english language.

Unit Of Work and Autofac Container

$
0
0

Question: 

I have a project that implements the Unit Of Work.  Typically I execute the unit of work utilizing ausing statement.  Reading the Autofac documentation, it says to "create a child lifetime scope from the the container and resolve from that".  In the class that I want to use my unit of work, do I use constructor injection to inject an ILifetimeScope so I can create my child lifetime scope?

using (var scope = container.BeginLifetimeScope())
{
    var uow = scope.Resolve<IUnitOfWork>();

    // do something

    uow.Complete();
}

Autofac Documentation:  Application Execution Section

During application execution, you’ll need to make use of the components you registered. You do this by resolving them from a lifetime scope.

The container itself is a lifetime scope, and you can technically just resolve things right from the container. It is not recommended to resolve from the container directly, however.

When you resolve a component, depending on the instance scope you define, a new instance of the object gets created. (Resolving a component is roughly equivalent to calling “new” to instantiate a class. That’s really, really oversimplifying it, but from an analogy perspective it’s fine.) Some components may need to be disposed (like they implement IDisposable) - Autofac can handle disposing those components for you when the lifetime scope is disposed.

However, the container lives for the lifetime of your application. If you resolve a lot of stuff directly from the container, you may end up with a lot of things hanging around waiting to be disposed. That’s not good (and you may see a “memory leak” doing that).

Instead, create a child lifetime scope from the container and resolve from that. When you’re done resolving components, dispose of the child scope and everything gets cleaned up for you.

Example from Autofac Documentation

namespace DemoApp
{
  public class Program
  {
    private static IContainer Container { get; set; }

    static void Main(string[] args)
    {
      // ...the stuff you saw earlier...
    }

    public static void WriteDate()
    {
      // Create the scope, resolve your IDateWriter,
      // use it, then dispose of the scope.
      using (var scope = Container.BeginLifetimeScope())
      {
        var writer = scope.Resolve<IDateWriter>();
        writer.WriteDate();
      }
    }
  }
}

Error on updating database / erasing last migration

$
0
0

If I have a problem updating database after a migration and get an error (below) trying to create a new migration to reverse the changes that prevented the database update...

Unable to generate an explicit migration because the following explicit migrations are pending: [201901281242341_ScheduleCalendarDate1]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

...and want to eliminate the last migration, can I simply delete the last migration folder in the the migration folder under Solution Explorer?

Or, in other words, how do I eliminate the last migration?

Viewing all 1698 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>