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

Seeding users using UserManger and Identify role class thinks its a static class

$
0
0

I am trying to seed users and permissions but no matter what I do I get the following error.

But when you look below at my code not one method is a static method so why on earth is visual studio claiming its a static class I dont want to it to be a static one?.

Severity Code Description Project File Line Suppression StateError CS1106 Extension method must be defined in a non-generic static class Warehouse.Web D:\GitMaster\WareHouseCrm\Warehouse.Web\Helpers\SeedUsers.cs 14 Active

Line 14 happens to be this line

public class SeedUsers

namespace WarehouseCrm.Web.Helpers
{
    public class SeedUsers
    {
        private WarehouseDBContext _context;

        public SeedUsers(WarehouseDBContext context)
        {
            _context = context;
        }

        public async void SeedRoles()
        {
            var roleStore = new RoleStore<IdentityRole>(_context);
            await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" });
            await roleStore.CreateAsync(new IdentityRole { Name = "manager", NormalizedName = "manager" });
            await roleStore.CreateAsync(new IdentityRole { Name = "agent", NormalizedName = "agent" });


        }
        public  async void SeedAdminUser(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, RoleStore<IdentityRole> roleStore, UserStore<ApplicationUser> userStore)
        {
            var user = new ApplicationUser
            {
                UserName = "testmanager@outlook.com",
                NormalizedUserName = "testmanager@outlook.com",
                Email = "testmanager@outlook.com",
                NormalizedEmail = "testmanager@outlook.com",
                FirstName = "test",
                LastName = "manager",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()
            };         
                var password = new PasswordHasher<ApplicationUser>();
                var hashed = password.HashPassword(user, "Test12345!");
                user.PasswordHash = hashed;
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, "admin");           
        }

        public  async void SeedUser1(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, RoleStore<IdentityRole> roleStore, UserStore<ApplicationUser> userStore)
        {
            var user = new ApplicationUser
            {
                UserName = "user1@test.com",
                NormalizedUserName = "user1@test.com",
                Email = "user1@test.com",
                NormalizedEmail = "user1@test.com",
                FirstName = "Martha",
                LastName = "Jones",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()
            };       

 
                var password = new PasswordHasher<ApplicationUser>();
                var hashed = password.HashPassword(user, "Test12345!");
                user.PasswordHash = hashed;
                  await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, "agent");
        }
        public  async void SeedUser2(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, RoleStore<IdentityRole> roleStore, UserStore<ApplicationUser> userStore)
        {
            var user = new ApplicationUser
            {
                UserName = "user2@test.com",
                NormalizedUserName = "user2@test.com",
                Email = "user2@test.com",
                NormalizedEmail = "user2@test.com",
                FirstName = "Matt",
                LastName = "Smith",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()
            };
                var password = new PasswordHasher<ApplicationUser>();
                var hashed = password.HashPassword(user, "Test12345!");
                user.PasswordHash = hashed;
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, "agent");
        }
        private  async Task SeedClaimsForSuperAdminAsync(this RoleManager<IdentityRole> roleManager)
        {
            var adminRole =await roleManager.FindByNameAsync("admin");
            await AddPermissionClaim(roleManager,adminRole, "StockItems");
        }
        public List<string> GeneratePermissionsForModule(string module)
        {
            return new List<string>()
            {$"Permissions.{module}.Create",$"Permissions.{module}.View",$"Permissions.{module}.Edit",$"Permissions.{module}.Delete",
            };
        }
        public  async Task AddPermissionClaim( RoleManager<IdentityRole> roleManager, IdentityRole role, string module)
        {
            var allClaims = await roleManager.GetClaimsAsync(role);
            var allPermissions = GeneratePermissionsForModule(module);
            foreach (var permission in allPermissions)
            {
                if (!allClaims.Any(a => a.Type == "Permission" && a.Value == permission))
                {
                    await roleManager.AddClaimAsync(role, new Claim("Permission", permission));
                }
            }
        }
    }

}


Scaffold common base class for all entities

$
0
0
Creating ASP.NET 5 Core MVC application using Npgsql EF Core provider.

Scaffold creates Poco classes like

    namespace MyDbContext
    {
        public partial class Customer
        {
            public Customer()
            {
            }
    
            public string Id { get; set; }
            public string Name { get; set; }
       }
    }


How to force it to generate common base class for all entities like

        public partial class Customer : EntityBase
        { }

or generic base class

      public partial class Customer : EntityBase<Customer>
        { }

Scaffold is perfomed at runtime. So it it not possible to manually change created code or add partial classes for every table.
Docs in https://docs.microsoft.com/en-us/ef/core/managing-schemas/scaffolding does not describe such option in

    dotnet ef dbcontex

command.

Help with composing async Task .....

$
0
0

I must select distinct values from one column named YEAR from the database table.  I MUST use async Task<IEnumerable<variables>> for this code in my class library.

I need help with the body of the code in the class library. The goal is to return a list ofDistinct Years from the database table.

Code - need linq code.

public async Task<IEnumerable<mRequestTbl>> GetFiscalYearList()

{

      return await_RequestTblRepository....... <-- HELP!!!

}

Help retrieving columns from StoredProcedure using LINQ...

$
0
0

I need to retrieve data by using a stored Procedure using MVC LINQ.   I need to retrieve two fields from the table.

My method is a public async Task IEnumerable and inside the body needs to return two columns from the stored procedure. There are no parameters for this stored procedure. The goal is to return the two columns from the stored procedure.

Columns: FullName, ClarkId

Method - code

public async Task<IEnumerable<ListClerks>> GetAllClerks()

{

   I need to be able to return list of clerks -- Please help

}

Your expertise is greatly appreciated. Thank you.

Linq GroupBy and Sum - .First() could not be translated

$
0
0

My data is owner, location, date, charge, payment, the plan is to get a list of owners, each having a location, and the Sum OwnerTotal (charge - payamount)

OwnerIdLocationChargePayAmount
1Loc 11000
1Loc 16050
1Loc 1800
2Loc 21000
2Loc 2800
1Loc 1190
2Loc 2180

[Route("ByProviderBilled")]
[HttpGet]
        public async Task<ActionResult<List<TxnsByProvider>>> GetByProviderBilled(int id, bool isbilled) => await context.Transactions
            .Where(p => p.ProviderId == id && p.IsBilled == isbilled).GroupBy(x => x.OwnerBillToId)
            .Select(txn => new TxnsByProvider
            {
                ownerBillToId = (int)txn.First().OwnerBillToId,
                Location = txn.First().OwnerLocation.Location,
                OName = txn.First().OwnerBillTo.Oname,
                OwnerTotal = (decimal)txn.Sum(o => o.Charge - o.PayAmount)
            })
            .OrderByDescending(t => t.OName)
            .ToListAsync();

.Select(s => s.OwnerBillToId)
          .First()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync

Really don't want to take Transactions into memory as is suggested, so maybe there is a different approach I can take without First()?

EF Core 5 - Does the order of Include()/Where() methods in queries matter?

$
0
0

I am upgrading from .NET Core 2.2 to .NET 5.0 one major release at a time (2.2 -> 3.0 -> 3.1 -> 5.0), and I have a LINQ query into a MySQL database that works differently after the upgrade to 5.0. The query works fine in 2.2, 3.0, and 3.1, but after the upgrade to 5.0 one of the Include() calls does not seem to have any effect. The query is:

var adminClient = (this._context.AdminUserClients    .Include(f => f.Client)    .Where(f => f.User.Id == user.Id && f.Client.Id != 1)    .Include(f => f.Client.ClientUserRoles)  // This Include does not seem to have an effect    .ThenInclude(f => f.User)    .FirstOrDefault())?.Client;

(See below for the model.)

When this runs in EF Core 3.1 (2.2 and 3.0 are similar) it generates a SQL statement with two subqueries, one to joinAdminUserClients, AspNetUsers, and Clients, and one to joinClientUserRoles and AspNetUsers. Then, it joins the two subqueries to generate the result. In EF Core 5.0, the generated SQL statement does not referenceClientUserRoles--it is essentially just the first subquery in the 3.1 SQL statement.

If I modify the query to move the Where() call after the Include() calls, it works:

var adminClient = (this._context.AdminUserClients    .Include(f => f.Client)    .Include(f => f.Client.ClientUserRoles)  // This Include runs fine    .ThenInclude(f => f.User)    .Where(f => f.User.Id == user.Id && f.Client.Id != 1)    .FirstOrDefault())?.Client;

In this case, the generated SQL statement is virtually identical to the one generated in 3.1.

I am not sure why this makes a difference. Maybe the User object needs to be included before it is referenced in theWhere() method? But that doesn't make sense to me because (1) it works in 2.2, 3.0, and 3.1, and (2) my understanding is that the relative order of the Include() and Where() methods should not impact the return set (though I get that it can impact performance).

Questions

  1. Is there a problem with the ordering of the Include() and Where() methods in the original query?
  2. Is there a change from EF Core 3.1 to EF Core 5.0 that would cause the behavior of this query to change?

Note on Split Queries

Because I am upgrading from 2.2 to 5.0, I am using UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) to emulate the 2.2 behavior. However, I have tested:

  1. Adding AsSplitQuery() to the query.
  2. Using UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery).
  3. Removing UseQuerySplittingBehavior() entirely.

In all of these cases, the behavior is the same.

Model

public class AdminUserClient
{    public long Id { get; set; }    [Required]    public ApplicationUser User { get; set; }    [Required]    public Client Client { get; set; }    [Required]    public DateTime CreatedOn { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public UserNotificationsSetting NotificationSetting { get; set; }    [JsonIgnore]    public ClientUserRole ClientUserRole { get; set; }    public bool Locked { get; set; }    public string Name { get; set; }
}

public class Client
{
    public long Id { get; set; }    public string Name { get; set; }    public string Description { get; set; }    public bool RequireTwoFactor { get; set; }    public ApplicationUser CreatedBy { get; set; }    public DateTime CreatedOn { get; set; }    [JsonIgnore]    public ICollection<ClientUserRole> ClientUserRoles { get; set; }    public bool IsDeleted { get; set; }    public bool Locked { get; set; }
}

public class ClientUserRole
{
    public long Id { get; set; }    [Required]    public long ClientId { get; set; }    [JsonIgnore]    public Client Client { get; set; }    [Required]    public string UserId { get; set; }    public ApplicationUser User { get; set; }    [Required]    public ApplicationUser CreatedBy { get; set; }    [Required]    public DateTime CreatedOn { get; set; }    [Required]    [Column(TypeName = "nvarchar(15)")]    public UserRole Role { get; set; }
}

EF Core 5.0.X Model Customizations - database first

$
0
0

I am modernizing a 4.X aspnet app to Blazor  Server/Wasm.

In the original app I was using EF 6.4.X and a whole bunch of model customizations. Been looking for how I can stil use these but all I find is for code first approach.

namespace BtServer.Data
{
    public class BtServerContext : IdentityDbContext<IdentityUser>
    {
        public BtServerContext(DbContextOptions<BtServerContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
}

How does this work in database first approach?

Editing SQL database items and Model Binding attributes?

$
0
0

Problem: I want to update an SQL database record and not create a new database entry.

The ASP.Net Core MVC application I am working on involves inventory tracking.  Data are stored in an MS SQL server database, by means of Entity FrameworkCore and LocalHost.  That all seems to be working well.  

Once a PullHdr (pull header) object has been stored I want to enable editing to display and update the order Status.  Users can select a Pull from a <select> element rendered in a Razor View.  The individual Pull is then displayed in another Razor view named PullDisplay.cshtml.  I have enabled the Status property of the PullHdr type with a dropdown list to update the Status property of the order.  Individual PullItems are also displayed on the form/view with the intent of updating the quantities ordered and shipped. PullDisplay.cshtml receives a PullDisplayViewModel as data source which contains a PullHdr object (PHdr) and a Dictionary<str, str> of Item descriiptions..

I've not made it past editing PullHdr.Status.  Once a PullHdr object is displayed and the Status changed I call the PullHdrChanged(PullHdr phdr) action method.  Status and other fields are sent to PullHdrChanged method and arrive intact.  However, the PullHdrId, which is the primary key in the SQL database is not carried forward from the PullDisplay View to the PullHdrChanged action method, nor are the individual PullItems from the PullItemList.  PullHdrId is an integer type and is reset to zero. Rather than updating the existing record, a zero value for PullHdrId causes a new PullHdr object to be created, that has the correct Status, but none of the PullItems from the list. 

I've used typical <label><input>  structures for all the properties except PullHdrId where I use the following:

<input type="hidden" asp-for="PHdr.PullHdrId" value="@Model.PHdr.PullHdrId" />

where PHdr is the PullHdr object from the view model.  How do I pass the PullHdrid back to the posting method and tell SQL server to save the updated values and not create a new instance of PullHdr?

Any constructive comments would be deeply appreciated.


Walking into an antipattern? Fetching data multiple FKs many layers deep ...

$
0
0

Using SQL and EF Core, I need to efficiently fetch data scattered across many tables.

There are ~50 tables, with many tables having multiple FK relationships, and the layers of FK relationships run up to about 5 layers deep. Almost all are one-to-many where "many" is less than 10. There is one table that all FK relationships eventually flow back to, and which defines the subset of data (<4MB) that a discrete set of calculationsworks on (consider it a unit of work in the business domain) .

Simplistically I could load that one parent entity and  -- via a ridiculous number of .Include() and .ThenInclude() LINQ statements -- I could get all the dependent data I need. I could run the calculations, make sure everything is okay, and then SaveChanges() to commit a coherent and correct unit of work back to the database.

However the ThenInclude() approach explodes into slow queries shockingly quickly, and so I find myself calling context.Entry(Foo).Collection(x => x.Bars).Load() many times within loops to fetch data just before it is needed.  All those small trips to the database are making me queasy, although so far in my dev-scale database it seems to be working fine. Perhaps is spreads out the load nicely. (Famous last words, I fear.)

  • Do you have any EF advice (relative to my ThenInclude() and Load() mentions) for efficiently fetching data scattered across dozens of tables to build my scope of calculations?
  • Thinking ahead to Azure SQL latency and async/await, how should I adjust my approach?

Thanks in advance. 

LINQ and Entity Framework errors

$
0
0

I have two tables in SQL database:

Challenger (ChallengerID, FirstName, LastName, Email)
Rank (RankID, ChallengerID, Best, DateAcheieved)

 and using entity framework to access data. When I am trying to select columns from both tables i always get an error. What am I doing wrong? Thank you

Dim db As New MemoryGameEntities
Dim query = From t1 In db.Challengers
                        From t2 In db.Ranks
                        Where t1.ChallengerID = t2.ChallengerID And t2.Best = 1
                        Select (t1.ChallengerID, t1.FirstName, t1.LastName, t1.Email, t2.DateAchieved)

How to use Clause "IN"

$
0
0

Hi All,

How can I passed array companies id into the .Where highlight orange query below:-

var companies = companies.Where(c=>!c.Id.Equals(0)).Select(c => c.Id).Distinct().ToList();             RequestEntityDataSource.Where = $"it.Company.Id IN (String.Join(",",{companies} ))&& " +                                                   $"(it.Status = {(int)Status.Saved} || it.status = {(int)Status.Ordered}) && " +                                                  "(it.Id = @IdFilter || @IdFilter = -1) &&" +                                                  "(it.CreatedBy LIKE '%' + @createdByFilter + '%' || @createdByFilter is null) &&" +                                                  "(it.PtName LIKE '%' + @pNameFilter + '%' || @PNameFilter is null) &&" +                                                  "(it.EndUser LIKE '%' + @endUserFilter + '%' || @endUserFilter is null) &&" +                                                  "(it.Name LIKE '%' + @NameFilter + '%' || @NameFilter is null)";

Error:

The query syntax is not valid. Near term ',', line 6, column 23.

Please advise.

Thanks

Regards,

Micheale

Is there a way to get a link query to return a row from a table?

$
0
0

So I am trying to access a database table that has a field that I need to match and if there is a match I need to select data out a field in  that table. I have tried and few things and I am coming up with nothing. 

So here is what I have so far

    Function GetCurrentUserEmail() As String

        'Get Current System Client Info
        'Check xxxxx View to get the User's Email 

        Dim CurrentUser As String = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name
       
'Dim Users As VUE_xxxxxx_EMPLOYEE_DIVISONS = XXXdb.VUE_xxxxx_EMPLOYEE_DIVISONS.SingleOrDefault(Function(u) u.Network_ID.Contains(CurrentUser)) 'Dim UserEmail = Users.Email.ToString() Dim UserEmail = From Users In XXXdb.VUE_XXXX_EMPLOYEE_DIVISONS Where Users.Network_ID = "%" & CurrentUser & "%," Select Users.Email Dim Test = UserEmail.ToString() Return Test End Function

What I would like to have is a Sql "Like" selection 

So if the Current User matches the network ID then I want to select that users email address from the table and send it back to the 

function that called it. 

I find link a bit confusing as there is more than one way to wright a query but there is never giving any reasons why you would use the lambda thing over the from option.

Same with where.  I thought contain would work but that seems like a useless option.

But any help or guidance would be most appreciated! Thanks

Sum and Case to linq

$
0
0

Need help to convert sql to linq in c#

SELECT    SUM(CASE WHEN Evaluation.StatusId = 3 THEN 1 END)AS EvalutionOK,
        SUM(CASE WHEN Evaluation.StatusId = 4 THEN 1 END) AS EvalutionTodo, 
        SUM(CASE WHEN Evaluation.StatusId = 2 THEN 1 END) AS EvalutionNOk
FROM Investor   
INNER JOIN Evaluation ON Evaluation.InvestorId = [dbo].[Investor].Id    

Sql Result :

EvalutionOK    EvalutionTodo    EvalutionNOk
5                       NULL                  NULL


List<Investor> Investors = ObjectSet.Include(z =>z.Evaluation).ToList();

var test = from i in Investors 
                       select new TestModel
            { 
                EvalutionTodo = i.Evaluation.Sum(e => e.StatusId == 3? 1 : 0),
                EvalutionOK = i.Evaluation.Sum(e => e.StatusId == 4? 1 : 0),
                EvalutionNOk = i.Evaluation.Sum(e => e.StatusId == 2? 1 : 0),
 };

C# result :

Result list  of TestModel

EvalutionOK    EvalutionTodo    EvalutionNOk
1                       0                          0

1                       0                          0

1                       0                          0

1                       0                          0

1                       0                          0

What i am missing? Any help ? How to get sum in sigle liek sql resut ? 

Thanks

executeScalar method is giving error

$
0
0

Hi All,

public string execCount(string query)
        {
            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {

                SqlCommand cmd = new SqlCommand(query,con);
               cmd.Connection = con;
                string count = cmd.ExecuteScalar().ToString();
               

                return count;
            }
        }

It is giving me error saying that 

ExecuteScalar requires an open and available Connection. The connection's current state is closed. What is the error here?

Thanks

listbox does not show the data

$
0
0

   public DataTable getCourses()
        {
            string CS = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {

                SqlCommand cmd = new SqlCommand("select * from course", con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }

public void ListBoxData()
        {
          
            ListBox1.DataSource = getCourses();
            ListBox1.DataTextField = "id";
            ListBox1.DataValueField = "label";

              }

On page_load i am trying to call this method but listbox doesn't display any data.


Can't migrate Entity Framework

$
0
0

Hi

I run this command on package manager console :

pm>add-migration FirstAppDemo

but keeping get this image:

The project first app demo failed to build.

What should I do?

please inform.

regards

Saeed

Number of rows returned by a DataReader

$
0
0
Hi, Is there any way to know how many rows the data reader returns after executing a SQL statement? For now, I am doing the follwing:if datareader.hasrows then while datareader.read count += 1 end while end ifBut this method has its own problems. I think the "hasrows" property messes with the "read" method somehow, because if my datareader returns just 1 row, then it enters the if statement above, but doesn't go into the while statement!! Strange!!! please help if you can. Thanks a lot.

Files under Miles under Model.tt

$
0
0

All the Entity classes under my Model.tt file are not included in TFS.  

I had the EDMX have an issue and had to restore it from TFS.  all the files underneath have a blue arrow next to them.

Any suggestions on how to get them added?

How to find duplicate records merge in MS.SQL

$
0
0

Hi Friends, 

Please ref my script, based on the GroupID, find the duplicate rows then merge, when VillageID Null/Zero the record can be removed.

SQL Table Script:

Create Table #T_Location(BranchID Int, ClusterID INT, ClusterName Varchar(100),VillageID INT, VillageName Varchar(100) ,GroupID INT,GroupName Varchar(100))

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		501,		'Neeradi Nagar', 3001,		'Defense Rx',	12,			'PPC 1991 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		501,		'Neeradi Nagar', '',			'',			12,		'PPC 1991 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		503,		'PTS Ave',		'',			'',				15,		'IAF 1991 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		503,		'PTS Ave',		3006,		'X Crook',		16,			'BSF 1994 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		503,		'PTS Ave',		'',			'',				16,			'BSF 1994 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		507,		'OMR YX Block', '',			'',				20119,		'YX V 1981 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		507,		'OMR YX Block', 3008,		'Zinc Force',	20120,		'YX V 1982 Batch')

INSERT INTO #T_Location(BranchID,	ClusterID,	ClusterName,	VillageID,	VillageName,	GroupID,	GroupName)
Values				   (100,		507,		'OMR YX Block', '',			'',				20120,		'YX V 1982 Batch')

Select * from #T_Location

BranchIDClusterIDClusterNameVillageIDVillageNameGroupIDGroupName
100501Neeradi Nagar3001Defense Rx12PPC 1991 Batch
100501Neeradi Nagar0 12PPC 1991 BatchBased on the GroupID, if Village id is null or Zero, this duplicate row can be removed 
100503PTS Ave0 15IAF 1991 Batch
100503PTS Ave3006X Crook16BSF 1994 Batch
100503PTS Ave0 16BSF 1994 BatchBased on the GroupID, if Village id is null or Zero, this duplicate row can be removed 
100507OMR YX Block0 20119YX V 1981 Batch
100507OMR YX Block3008Zinc Force20120YX V 1982 Batch
100507OMR YX Block0 20120YX V 1982 BatchBased on the GroupID, if Village id is null or Zero, this duplicate row can be removed 

Expected Result:

BranchIDClusterIDClusterNameVillageIDVillageNameGroupIDGroupName
100501Neeradi Nagar3001Defense Rx12PPC 1991 Batch
100503PTS Ave0 15IAF 1991 Batch
100503PTS Ave3006X Crook16BSF 1994 Batch
100507OMR YX Block0 20119YX V 1981 Batch
100507OMR YX Block3008Zinc Force20120YX V 1982 Batch

Thanks in advance. 

Visual Studio can't load MySql.Data.EntityFramework

$
0
0

I'm trying to synchronize an old .net application with Visual Studio 2019. However, I'm getting the error below when I try to open the ADO.NET

Severity	Code	Description	Project	File	Line	Suppression State
Error		Error 4: Could not load file or assembly 'MySql.Data.EntityFramework, Version=8.0.21.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)	iRentFeedData	C:\Users\giova\OneDrive\Documents\Visual Studio 2019\Projects\ProName\ProdName\Models\myModel.edmx	7	

I have MySQL Connector Net 8.0.21 installed. Also, I have MySql.Data version: 8.0.21.0 and MySql.Data.EntityFramework version: 8.0.21.0

Here is my webconfig:

<?xml version="1.0" encoding="utf-8"?><!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  --><configuration><configSections><section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --><sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core"><section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /><section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /><section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" /><section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" /></sectionGroup><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections><appSettings></appSettings><system.web><compilation debug="true" targetFramework="4.5.2" /><httpRuntime targetFramework="4.5.2" /></system.web><runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" /></dependentAssembly></assemblyBinding><!-- This prevents the Windows Event Log from frequently logging that HMAC1 is being used (when the other party needs it). --><!-- This prevents the Windows Event Log from frequently logging that HMAC1 is being used (when the other party needs it). --><legacyHMACWarning enabled="0" /><!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink
		     to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it.<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /></dependentAssembly></assemblyBinding>
		 --></runtime><connectionStrings><add name="myEntities" connectionString="metadata=res://*/Models.myModel.csdl|res://*/Models.myModel.ssdl|res://*/Models.myModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;server=vps.myserver.com;user id=myUser;password=myPass;database=mydb&quot;" providerName="System.Data.EntityClient" /></connectionStrings><entityFramework><defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /><providers><provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework, Version=8.0.21.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers></entityFramework><system.webServer><handlers><remove name="ExtensionlessUrlHandler-Integrated-4.0" /><remove name="OPTIONSVerbHandler" /><remove name="TRACEVerbHandler" /><add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers><httpProtocol><customHeaders><add name="Access-Control-Allow-Origin" value="*" /><add name="Access-Control-Allow-Headers" value="Content-Type" /><add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /></customHeaders></httpProtocol></system.webServer><system.net><defaultProxy enabled="true" /><settings><!-- This setting causes .NET to check certificate revocation lists (CRL) 
			     before trusting HTTPS certificates.  But this setting tends to not 
			     be allowed in shared hosting environments. --><!--<servicePointManager checkCertificateRevocationList="true"/>--><!-- This setting causes .NET to check certificate revocation lists (CRL) 
			     before trusting HTTPS certificates.  But this setting tends to not 
			     be allowed in shared hosting environments. --><!--<servicePointManager checkCertificateRevocationList="true"/>--></settings></system.net><dotNetOpenAuth><messaging><untrustedWebRequest><whitelistHosts><!-- Uncomment to enable communication with localhost (should generally not activate in production!) --><!--<add name="localhost" />--></whitelistHosts></untrustedWebRequest></messaging><!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --><reporting enabled="true" /><!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. --><!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ --><openid><relyingParty><security requireSsl="false"><!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. --><!--<trustedProviders rejectAssertionsFromUntrustedProviders="true"><add endpoint="https://www.google.com/accounts/o8/ud" /></trustedProviders>--></security><behaviors><!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
					     with OPs that use Attribute Exchange (in various formats). --><add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" /></behaviors></relyingParty></openid></dotNetOpenAuth><uri><!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
		     which is necessary for OpenID urls with unicode characters in the domain/host name.
		     It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. --><idn enabled="All" /><iriParsing enabled="true" /></uri></configuration>

I already reinstall the MySql.Data.EntityFramework, but it did not solve the issue. Any idea of waht is happening?

Thank you!


  

 

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

Viewing all 1698 articles
Browse latest View live


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