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

Invalid column name 'UserId'.

$
0
0

Hello,

I am using ASP MVC ENTITY FRAMEWORK CODE FIRST. I have a table called "Voiture" which contains 4 fields. I am trying now to add a new field UserID by writing this in my Class Voiture.cs :

[Required]
public String UserId { get; set; }

in order to show only the data related of the logged User, I wrote this in my Controller :

 return View(db.Voitures.Where(a => a.UserId == HttpContext.User.Identity.Name).ToList());

but I got always this Error :

Invalid column name 'UserId'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'UserId'.


Filter Products by Atributes : How to optimize queries in Entity Core, SQL Server 2016

$
0
0

I need an expert solution to optimize some queries in Entity Core, SQL Server 2016 (Azure or virtual) for a few real world applications.

I have tested the app with 10 Products, 4 Attributes, 10 Atribute Values and i get a very big time for query execution: 2 seconds – 3 seconds and this is not ok. I think I am missing something.

Example:

We have an app who need to filter the products by attributes and filter the attributes by current selected attributes . Ex: Query Products with (2 Gb or 4 Gb) and (Red Colour or Blue Colour)

Memory

  • 2 Gb (2)
  • 4 Gb (3)

Dimmension

  • 2 Gb (2)
  • 4 Gb (3)

Colour

  • Red (2)
  • Blue (3)

 The Database structure is:

Products (ProductID)

Atributes (AtributeID, Title) (ex: Memory),

AtributeValues(AtributeValueID, AtributeID, Title) (ex: 2 GB)

Product Atributes (ProductAtributeID, ProductID, AtributeID, AtributeValueID)

We need to optimize the Queries 

1.     Filter Products By Selected AtributeValues

1.1  Select Product List By Selected AtributeValues

public static async Task<List<Product>> GetProductsByAtributes(this DbSet<Product> source, List<AtributeValue> Filters, int? Page, int PageSize)
{
  List<Product> rets;
  var query = source. AsQueryable();
foreach (var filtersGroup in Filters.GroupBy(p => p.AtributeID)) { int atributeID = filtersGroup.Key; var atributeValues = filtersGroup.Select(p => p.AtributeValueID); query = query.Where(p => p.ProductAtributes.Any(y => y.AtributeID == atributeID && atributeValues.Contains(y.AtributeValueID))); } rets = await query.Skip(PageIndex * PageSize).Take(PageSize).AsNoTracking().ToListAsync(); return rets; }

SQL Translation: 

 Executed DbCommand (1,746ms)

SELECT *...
      FROM [Products] AS [p]
      WHERE ( EXISTS (
          SELECT 1
          FROM [ProductAtributes] AS [y]
          WHERE (([y].[AtributeID] = @__atributeID_5) AND [y].[AtributeValueID] IN (25)) AND ([p].[ProductID] = [y].[ProductID]))) AND EXISTS (
          SELECT 1
          FROM [ProductAtributes] AS [y0]
          WHERE (([y0].[AtributeID] = @__atributeID_7) AND [y0].[AtributeValueID] IN (32)) AND ([p].[ProductID] = [y0].[ProductID]))) AND EXISTS (
          SELECT 1
          FROM [ProductAtributes] AS [y1]
          WHERE (([y1].[AtributeID] = @__atributeID_9) AND [y1].[AtributeValueID] IN (50)) AND ([p].[ProductID] = [y1].[ProductID]))
      ORDER BY [p].[ProductID] DESC
      OFFSET @__p_11 ROWS FETCH NEXT @__p_12 ROWS ONLY

1.2 SelectProducts Count  By Selected AtributeValues (Need for paging)

public static async Task<int> GetProductsCountByAtributes(this DbSet<Product> source, List<AtributeValue> Filters int? Page, int PageSize)
{
  int ret;
  var query = source. AsQueryable();
  foreach (var filtersGroup in Filters.GroupBy(p => p.AtributeID))
  {
    int atributeID = filtersGroup.Key;
    var atributeValues = filtersGroup.Select(p => p.AtributeValueID);
    query = query.Where(p => p.ProductAtributes.Any(y => y.AtributeID == atributeID && atributeValues.Contains(y.AtributeValueID)));
 }

 ret = await query.CountAsync();
 return ret;
}

SQL Translation

 Executed DbCommand (1,948ms)

  SELECT COUNT(*)
      FROM [Products] AS [p]
      WHERE ( EXISTS (
          SELECT 1
          FROM [ProductAtributes] AS [y]
          WHERE (([y].[AtributeID] = @__atributeID_5) AND [y].[AtributeValueID] IN (25)) AND ([p].[ProductID] = [y].[ProductID]))) AND EXISTS (
          SELECT 1
          FROM [ProductAtributes] AS [y0]
          WHERE (([y0].[AtributeID] = @__atributeID_7) AND [y0].[AtributeValueID] IN (32)) AND ([p].[ProductID] = [y0].[ProductID]))) AND EXISTS (
          SELECT 1
          FROM [ProductAtributes] AS [y1]
          WHERE (([y1].[AtributeID] = @__atributeID_9) AND [y1].[AtributeValueID] IN (50)) AND ([p].[ProductID] = [y1].[ProductID]))


2.Select and Count Atributes and AtributeValues by Selected Atributes

public static async Task<List<Atribute>> GetAtributesBySelectedFiltersAsync(this DbSet<Atribute> source, ApplicationDbContext context, List<AtributeValue> Filters)
{
// get the attribute List List<Atribute> rets = await context.Atributes.AsNoTracking().ToListAsync();
if (rets != null) { var queryAtributesInt = rets.Select(p => p.AtributeID);
// Count Products By Selected Filters var queryProductsCount = context.Products.AsQueryable(); foreach (var filtersGroup in Filters.GroupBy(p => p.AtributeID)) { int atributeID = filtersGroup.Key; var atributeValues = filtersGroup.Select(p => p.AtributeValueID);queryProductsCount =
queryProductsCount.Where(p => p.ProductAtributes.Any(y => y.AtributeID == atributeID && atributeValues.Contains(y.AtributeValueID))); } var query = context.AtributeValues.Where(p => queryAtributesInt.Contains(p.AtributeID)).AsQueryable(); var querySelect = (filters.Count() > 0) == true ?

// if there are selected filters query.Select ( a => new { AtributeValueID = a.AtributeValueID, Title = a.Title, Importance = a.Importance, AtributeID = a.AtributeID, Count = queryProductsCount.Where(p => p.ProductAtributes.Any(av => av.AtributeValueID == a.AtributeValueID)).Count() } ).AsQueryable() :
// if there are not selected filters query.Select ( a => new { AtributeValueID = a.AtributeValueID, Title = a.Title, Importance = a.Importance, AtributeID = a.AtributeID, Count = a.ProductAtributes.Count() } ).AsQueryable(); var queryResult = await querySelect.OrderBy(p => p.Importance).AsNoTracking().ToListAsync();
// convert from anomymous
var atributeValueResults= new List<AtributeValue>();
foreach (var item in queryResult)
{
AtributeValue ret = new AtributeValue();
ret.AtributeID = item.AtributeID;
ret.AtributeValueID = item.AtributeValueID;
atributeValueResults.Add(ret);
} foreach (var item in rets) { item.AtributeValues = atributeValueResults.Where(p => p.AtributeID == item.AtributeID).ToList(); } } return rets; } 

SQL Translation

 Executed DbCommand (3,298ms)

      SELECT [p].[AtributeValueID], [p].[Title], [p].[Importance], [p].[AtributeID], (
          SELECT COUNT(*)
          FROM [Products] AS [p1]
          WHERE (((([p1].[IsPublished] = 1) AND EXISTS (
              SELECT 1
              FROM [ProductAtributes] AS [y2]
              WHERE ((([y2].[AtributeID] = @__atributeID_1) AND ([y2].[ProductCategoryID] = @__8__locals1_ProductCategoryID_2)) AND [y2].[AtributeValueID] IN (25)) AND ([p1].[ProductID] = [y2].[ProductID]))) AND (([p1].[IsPublished] = 1) AND EXISTS (
              SELECT 1
              FROM [ProductAtributes] AS [y3]
              WHERE ((([y3].[AtributeID] = @__atributeID_4) AND ([y3].[ProductCategoryID] = @__8__locals1_ProductCategoryID_5)) AND [y3].[AtributeValueID] IN (32)) AND ([p1].[ProductID] = [y3].[ProductID])))) AND (([p1].[IsPublished] = 1) AND EXISTS (
              SELECT 1
              FROM [ProductAtributes] AS [y4]
              WHERE ((([y4].[AtributeID] = @__atributeID_7) AND ([y4].[ProductCategoryID] = @__8__locals1_ProductCategoryID_8)) AND [y4].[AtributeValueID] IN (50)) AND ([p1].[ProductID] = [y4].[ProductID])))) AND EXISTS (
              SELECT 1
              FROM [ProductAtributes] AS [av0]
              WHERE (([av0].[ProductCategoryID] = @__8__locals1_ProductCategoryID_10) AND ([av0].[AtributeValueID] = [p].[AtributeValueID])) AND ([p1].[ProductID] = [av0].[ProductID]))
      )
      FROM [AtributeValues] AS [p]
      WHERE [p].[AtributeID] IN (31, 15, 18, 26, 28, 27)
      ORDER BY [p].[Importance]

 


An exception of type 'NHibernate.Exceptions.GenericADOException'

$
0
0

I am trying to make a registration. Everything is fine until the entity save with NHibernate, when this exception occurs: 

An exception of type 'NHibernate.Exceptions.GenericADOException' occurred in NHibernate.dll but was not handled in user code

Additional information: could not insert: [DataAccess.Model.PujcovnaUser][SQL: INSERT INTO pujcovna_user (name, surname, login, password, address, role_id) VALUES (?, ?, ?, ?, ?, ?); select SCOPE_IDENTITY()]

In debug mode, when i click continue, this pops up: 

Cannot insert the value NULL into column 'role_id', table 'Pujcovna_lyzi.dbo.pujcovna_user'; column does not allow nulls. INSERT fails.
The statement has been terminated.

However when i drag mouse on the entity, the role_id is correctly set and is not null.

USER MAPPING

<?xml version="1.0" encoding="utf-8" ?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="DataAccess"
                   namespace="DataAccess.Model"><class name="PujcovnaUser" table="pujcovna_user" lazy="false"><id name="Id" column="user_id"><generator class="native" /></id><property name="Name" column="name" /><property name="Surname" column="surname" /><property name="Login" column="login" /><property name="Password" column="password" /><property name="Address" column="address" /><many-to-one name="Role" column="role_id" foreign-key="role_id" /></class></hibernate-mapping>

ROLE MAPPING

<?xml version="1.0" encoding="utf-8" ?><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="DataAccess"
                   namespace="DataAccess.Model"><class name="PujcovnaRole" table="pujcovna_role"><id name="Id" column="Id"><generator class="native" /></id><property name="Identificator" column="identificator" /><property name="RoleDescription" column="role_description" /></class></hibernate-mapping>

USER CONTROLLER

 public class UserController : Controller
    {
        // GET: Admin/User
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {

            UserDao userDao = new UserDao();
            IList<PujcovnaUser> users = userDao.GetAll();
            ViewBag.Users = users;


            return View();
        }

        [HttpPost]
        public ActionResult Add(PujcovnaUser user)
        {
            if (ModelState.IsValid)
            {


                UserDao userDao = new UserDao();

                PujcovnaRoleDao roleDao = new PujcovnaRoleDao();
                PujcovnaRole role = roleDao.GetById(2);

                user.Role = role;

                userDao.Create(user);
                TempData["message-success"] = "Uživatel vytvořen";

            }

            else

            {
                return View("Create", user);
            }



            return RedirectToAction("Index");
        }
    }

 

Can you help me find the mistake please?

MS has any ready made project where repository pattern implemented with EF and unit test done

$
0
0

i am weak in unit test. so i am looking for a sample existing project like nerd dinner where EF will be used with repository pattern and unit test should be there for repository pattern. so if any exist then please share me the links. i search google and found tiny sample code on unit testing repository pattern but i am looking for a complete small sample project where EF will be used with repository pattern along unit test.

thanks

EF 6, ASP.NET 4.6.1, and GridView

$
0
0

Hi Folks,

I've been away from ASP.NET for a number of years but have been diving back in for a project I am working on currently.

It is essentially an event ticketing application, for church outreach events.

I pull the outreach events from our ChMS (like a CRM but for churches) via an API and add them into a MSSQL DB. I built the DB first, so I have an EDMX file generated off the DB using the EF Designer.

So far, so good. Now I began placing my GridView (and eventually I'll want a DetailsView and a method for registering for an event) and wiring it up to my EntityDataSource...ohhh wait, that isn't the way we do it anymore? Fine, so I'll perform the data binding via DbContext to the gridview in the page load and then manually add BoundFields for my desired columns.

But now I'm wondering if I'm going about this the best way. Should I use EDS? Should I drop using the GridView/DetailsView entirely and build my own grids/details views?

How would you handle this situation? I'm using Web Forms b/c that is what I'm familiar with and b/c this project needs to be done yesterday...I could jump into MVC/Razor, but not sure if there would be a significant advantage for me? Or of moving away from EDMX? 

I'm pretty good at learning things quickly, but there needs to be a significant payoff in the short-term for this particular project. Longer term, of course, I want to learn the better ways of doing things, but for this project I need results.

A few things to consider about the app's features when complete that may affect some of your answers to the above:

  • Each event has a relatively low number of slots available (e.g. 10, 20), I need to make sure that we don't overfill an event.
  • The events are things like serving dinner at a homeless shelter, playing bingo with the elderly, helping clean a local park, performing building/remodeling for non-profits, etc., etc.
  • In addition to registering individuals I need to include functionality to register groups (only a small group leader can do so) and families (only a member of the family can do so).
  • There is no cost associated with the events, but events do fit into different categories (e.g. family friendly, for individuals, for groups, meals, hands-on, etc.)

Any thoughts on how I can best proceed would be greatly appreciated.

Thanks!

Dave

Enity Frame work in webapi with all the tables in Database. In Database first approach. Error Self referencing loop detected.

$
0
0

Hi Every one,

I have a database with the multiple tables. i.e around 15 tables. And I have been using the Entity Frame used  EDMX to fetch Data.

I have added all the tables (15)in the EDMX.  My data base is well designed with all the Primary Keys and Foreign keys.

When I was using the webapi get and fetching the data its was showing me an error like infinite loop. 

Self referencing loop detected

But for test when I use 2-3 tables every thing is working fine.

Is there any thing I need to after adding all the tables in the EDMX file Auto Mapping(As my mapping was done while creating the data base).

Please any one help me fixing the issue.

Thank you 

Avenka.

Add data annotations to partial class

$
0
0

Hi!

I'm using DbFirst and I trying to add  data annotation to existing generated attributes.

inside edmx there is already this class

namespace POSweb.Models
{

    public partial class GS_POS_CO
    {
.....
        public long ID { get; set; }
.....
    }
}

To avoid code overwritten on model refresh I've created a new file Annotations.cs and inside add a new partial class with the same name for class and namespace:

namespace POSweb.Models
{

    [MetadataType(typeof(GS_POS_CO.Annotations))]
    public partial class GS_POS_CO
    {
      internal class Annotations
      {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long ID { get; set; }
      }
    }
} 

There is no error but my code doesn't seems to work,there must be the new class file added that I have to put is somewhere ?

thanks

How to update modified fields only

$
0
0

Hello 

I am using the attach to update only some fields as follow: 

https://forums.asp.net/post/6092146.aspx

context.Users.Attach(updatedUser);
var entry = context.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
context.SaveChanges();

But in this case, I have to write two classes, One for full user details and one for only some details, 

I found a blog that will go through all properties and change based on what is modified 

but It is not working with EF Core 

http://blog.aspjava.com/2014/09/entity-framework-update-only-changed.html

Even when I post data using FromBody and Json, some data passes as Null, that's why it is cleared from the database, 

So is there any way to check that? 

Thanks 


Convert tab delimited strings into a table format in C#

$
0
0

Hello,

I have some code that takes the SQL data from variables in a SSIS package and shows data in a tab delimited format.  Sometimes things don't lineup so I would like to convert it
to a table format. Here is the tab delimited format code and it's result.

Variables varCollection = null;
string header = string.Empty;
string message = string.Empty;

Dts.VariableDispenser.LockForWrite("User::Message");
Dts.VariableDispenser.LockForWrite("User::ObjectName");
Dts.VariableDispenser.LockForWrite("User::ObjectType");

Dts.VariableDispenser.GetVariables(ref varCollection);

//Set the header message for the query result
if (varCollection["User::Message"].Value == string.Empty)
{
var lastMonthYear = DateTime.Now.AddMonths(-1).ToString("Y");
var currentYear = DateTime.Now.Year;

header = "SQL Query Results:\n\n";

header += string.Format("{0}\t\t\t\t\t\t{1}\n", "Object Name", "Object Type");
varCollection["User::Message"].Value = header;
}

//Format the query result with tab delimiters
message = string.Format("{0}\t{1}\n",
varCollection["User::ObjectName"].Value,
varCollection["User::ObjectType"].Value );

varCollection["User::Message"].Value = varCollection["User::Message"].Value + message;
varCollection.Unlock();


//Here is how the result looks like which I send in an email:

Object Name-------Object Type
sp.MyProcedure----SQL_STORED_PROCEDURE
dbo.mytable-----SQL_USER_TABLE

I started the code for a table but am stuck on the looping part, where I need to see how many rows do I need to append. I can only do hard coded rows.

DataTable table = new DataTable();
table.Columns.Add("Object Name", typeof(string));
table.Columns.Add("Object Type", typeof(string));

// Here is how I can add hardcoded 2 rows but not sure how to add dynamic rows based upon the Dts.VariableDispenser collection, which could be 1- 50 in number.
table.Rows.Add("sp.MyProcedure", "SQL_STORED_PROCEDURE");
table.Rows.Add("dbo.mytable", "SQL_USER_TABLE");

If you have any suggestions then please let me know. Thanks

write extra fields to db

$
0
0

I have a .Net Core application in which I've created PhoneNumber and Email tables separate from the AspNetUser table for normalization sake (in other words, I anticipate having other types of users with phone and e-mail). In registering users, I want to their capture PhoneNumberId and EmailId from those tables and write them to AspNetUsers as foreign keys. However, I just can't wrap my head around how to write the phone and e-mail fields captured in the registration process to those other tables, and bring back the resulting IDs. Following is the relevant code so far in my Register method. Any ideas? Would Include statements be appropriate here? Thanks in advance.

//
		// GET: /Account/Register
		[HttpGet]
		[AllowAnonymous]
		public IActionResult Register(string returnUrl = null)
		{
			ViewData["ReturnUrl"] = returnUrl;
			return View();
		}

		//
		// POST: /Account/Register
		[HttpPost]
		[AllowAnonymous]
		[ValidateAntiForgeryToken]
		public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
		{
			ViewData["ReturnUrl"] = returnUrl;
			if (ModelState.IsValid)
			{

// write the phone and e-mail values to those tables

					var user = new AppUser
				{
					UserName = model.Email,
					FirstName = model.FirstName,
					LastName = model.LastName,
				};
				var result = await _userManager.CreateAsync(user, model.Password);

				if (result.Succeeded)
				{
					// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
					// Send an email with this link
					var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
					var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
					//await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
					await _signInManager.SignInAsync(user, isPersistent: false);
					_logger.LogInformation(3, "User created a new account with password.");
					return RedirectToLocal(returnUrl);
				}
				AddErrors(result);
			}

			// If we got this far, something failed, redisplay form
			return View(model);
		}

Viewing message from database

$
0
0

Hello I am working on a little project.  Where a user can send a message to another user on the application.  The controls have been created dynamically so that each time a message was sent a new message would appear in there inbox, or sent messages. When a message is visible it will show the user that sent the message, the subject, the date that it was sent. When a user clicks on the message or the subject the message will appear in sort of like a pop up window or splash screen.  The problem that I am having is that if I have to messages with the same subject line it will bring up both messages with that subject line rather then just the one that was clicked.  Below are the controls created dynamically

            Label[] Date = new Label[200];
            LinkButton[] UserId = new LinkButton[200];
            LinkButton[] Subject = new LinkButton[200];
            CheckBox[] delete = new CheckBox[200];

            int H = 0;
            for (int i = 0; i < 200; i++)
            {
                try
                {
                    read.Read();

                    UserId[i] = new LinkButton();
                    UserId[i].Font.Size = 20;
                    UserId[i].ID = "UserId" + i;
                    UserId[i].Style.Add("left", "300px");
                    UserId[i].Style.Add("position", "absolute");
                    UserId[i].Style.Add("top", H.ToString() + "px");
                    scroll.Controls.Add(UserId[i]);

                    Subject[i] = new LinkButton();
                    Subject[i].Font.Size = 20;
                    Subject[i].ID = "Subject" + i;
                    Subject[i].Style.Add("left", "600px");
                    Subject[i].Style.Add("position", "absolute");
                    Subject[i].Style.Add("top", H.ToString() + "px");
                    scroll.Controls.Add(Subject[i]);

                    Date[i] = new Label();
                    Date[i].Font.Size = 20;
                    Date[i].ID = "Date" + i;
                    Date[i].Style.Add("left", "900px");
                    Date[i].Style.Add("position", "absolute");
                    Date[i].Style.Add("top", H.ToString() + "px");
                    scroll.Controls.Add(Date[i]);

                    UserId[i].Text += read["ToUser"].ToString();
                    Subject[i].Text += read["Subject"].ToString();
                    Date[i].Text += read["SendDate"].ToString();
                    Time.Add(read["SendDate"].ToString());
                    Session["Time"] = Time;

                    UserId[i].Click += UserId_Click;
                    Subject[i].Click += Subject_Click;

                    delete[i] = new CheckBox();
                    delete[i].Font.Size = 20;
                    delete[i].ID = "delete" + i;
                    delete[i].Style.Add("left", "225px");
                    delete[i].Style.Add("position", "absolute");
                    delete[i].Style.Add("top", H.ToString() + "px");
                    scroll.Controls.Add(delete[i]);
                    delete[i].AutoPostBack = true;
                    delete[i].CheckedChanged += delete_Checked;

Also below is the event handler for when the subject was clicked

    protected void Subject_Click(object sender, EventArgs e)
        {

            LinkButton Subject = sender as LinkButton;

            //////ArrayList Time = (ArrayList)Session["Time"];

            SentMessage.Visible = true;

            string MyConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

            connection.ConnectionString = (MyConnection);
            connection.Open();

            SqlCommand Sent = new SqlCommand(@"Select Subject, Message FROM SentMessages WHERE Subject=@Subject", connection);


            //SqlCommand ProfilePage = new SqlCommand("Forevayoung.ProfilePage", connection);
            //ProfilePage.CommandType = System.Data.CommandType.StoredProcedure;


            //Sent.Parameters.AddWithValue("@SendDate", Time[0].ToString());


            Sent.Parameters.AddWithValue("@Subject", Subject.Text);

            SqlDataReader read = Sent.ExecuteReader();


            while(read.Read())
            {
                SubjectMessage.Text += read["Subject"].ToString();
                MessageBox.Text += read["Message"].ToString();
            }
            read.Close();

            connection.Close();
        }

Now I believe I understand exactly why it is doing what its doing, I just cant seem to come with a solution to fixing it.  Remember everything works fine when the subject line is different, but when I have two subject lines that are the same on the application, then when it is clicked it will bring up both messages, and not just that one that was clicked.  Any help would be greatly appreciated.  Thanks 

The entity type does not declare a navigation property with the name

$
0
0

Getting error:

A specified Include path is not valid. The EntityType 'StripeModel.Plan' does not declare a navigation property with the name 'Features'

My query

<div class="pre-action-link" id="premain479749"> </div>
var plans = (from p in db.Plans.Include("Features")orderby p.DisplayOrderselect p).ToList()

How to merge multiple List values in one list - Getting Error as Value cannot be null

$
0
0

How to merge multiple list values in one list values.

For example,

List<string> List1 = new List<string> {"A","B","C"}; // Some times null value also

List <string> List2 = new List<string> {"D","E","F"}; // Some times null value also

List <string> List3=  null;  // Some times null value also

My Query is below :

 List<string> ArrAllValue = List1.Concat(List2.Concat(List3))
                                                               .Where(x => !string.IsNullOrEmpty(x)) //probably
                                                               .ToList();

Error : Value Cannot be null

Looking for easy and normal repository design which help me to do CRUD operation

$
0
0

when i am searching google for repository design pattern with EF then i am getting most of the time generic repository design pattern with EF or complex code for normal repository design pattern. see a sample i got https://www.codeproject.com/Articles/37155/Implementing-Repository-Pattern-With-Entity-Framew

their code is very big and complex to understand.

so my request anyone can give me few links from where i can download sample code for easy repository design pattern with EF which help me to do CRUD operation.

please do not give me any link about generic repository design pattern with EF.

thanks

Entity Framework “An entity object cannot be referenced by multiple instances of IEntityChangeTracker”

$
0
0

I edit my object Reservation_House in following method.

public void ChangeAssignedMealsAndHouses(int id, NewReservation reservation)
        {
            foreach (KeyValuePair<string, int> item in reservation.AssignedHousesMeals)
            {
                string houseName = Regex.Match(item.Key, @"\(([^)]*)\)").Groups[1].Value;
                int houseId = db.Houses.Where(house => house.Name.Equals(houseName)).FirstOrDefault().Id;
                Reservation_House reservationHouse = (from resHouse in db.Reservation_House
                                                      where resHouse.ReservationId.Equals(id)&& resHouse.HouseId.Equals(houseId)
                                                      select resHouse).FirstOrDefault();
                reservationHouse.MealId = item.Value;
                db.Entry(reservationHouse).State = EntityState.Modified;

                ChangeAssignedHouseParticipants(reservationHouse.Id, reservation.AssignedParticipantsHouses[item.Key]);
                SaveChanges();
            }
        }

At some stage there is another execution of method called ChangeAssignedHouseParticipants. In this method I also modify some entity.

private void ChangeAssignedHouseParticipants(int reservationHouseId, List<Participant> participants)
        {
            foreach (Participant participant in participants)
            {
                db.Entry(participant).State = EntityState.Modified;
            }
        }

Both presented methods are in following class.

public class ReservationRepository : IReservationRepository
    {
        private readonly IAgrotourismContext db;
......
}

My context to database I obtain in this way.

private readonly IAgrotourismContext db;

        public ReservationRepository(IAgrotourismContext db)
        {
            this.db = db;
        }

I use UnityConfig for IOC.

UnityConfig.cs file.

public static void RegisterTypes(IUnityContainer container)
        {
ProductRepository>();
            container.RegisterType<AccountController>(new InjectionConstructor());
            container.RegisterType<ManageController>(new InjectionConstructor());
            container.RegisterType<IUserRepository,UserRepository>(new PerRequestLifetimeManager());
            container.RegisterType<IHouseRepository, HouseRepository>(new PerRequestLifetimeManager());
            container.RegisterType<IMealRepository, MealRepository>(new PerRequestLifetimeManager());
            container.RegisterType<IAttractionRepository, AttractionRepository>(new PerRequestLifetimeManager());
            container.RegisterType<IReservationRepository, ReservationRepository>(new PerRequestLifetimeManager);
            container.RegisterType<IAgrotourismContext, AgrotourismContext>(new PerRequestLifetimeManager());
        }
}

Problem is during updating participants. How can I solve it?


SQL Server Always Encryption - SSDT 2015

$
0
0

Hello,

I have an SQL server 2016 database where a column in a table is encrypted using Always encryption feature. I am using SSDT 2015 to import this table into tabular.

SSDT and SQL Server 2016 and SQL Server tabular Analysis service all are on a same machine.

column master key is generated for local machine in personal-certificate. i had given read access to the user account which SSDT is using to connect to database.

IN SSDT, i am using .Net Framwork Data Provider for SQL server with column encryption enabled but when i tried to deploy the model, give me an error message:

Failed to save modifications to the server. Error returned: 'The following exception occurred while the managed IDataReader interface was being used: Failed to decrypt column 'name'.
Failed to decrypt a column encryption key using key store provider: 'MSSQL_CERTIFICATE_STORE'. The last 10 bytes of the encrypted column encryption key are: '5
Keyset does not exist
;Keyset does not exist
.
'.

has anyone come across this issue and have a solution for this?

Thanks,

selecting messages from database

$
0
0

Hello I am working on a little project.  Where a user can send a message to another user on the application.  The controls have been created dynamically so that each time a message was sent a new message would appear in there inbox, or sent messages.  When a message is visible it will show the user that sent the message, the subject, the date that it was sent and also a check box that can be checked and delete the message.  When I check a message it shows that all message are checked in the database rather then just the one, and thats what I am trying to fix.  Here are the controls that are created dynamically.

Label[] Date = new Label[200];
LinkButton[] UserId = new LinkButton[200];
LinkButton[] Subject = new LinkButton[200];
CheckBox[] delete = new CheckBox[200];

int H = 0;
for (int i = 0; i < 200; i++)
{
try
{
read.Read();

UserId[i] = new LinkButton();
UserId[i].Font.Size = 20;
UserId[i].ID = "UserId" + i;
UserId[i].Style.Add("left", "300px");
UserId[i].Style.Add("position", "absolute");
UserId[i].Style.Add("top", H.ToString() + "px");
scroll.Controls.Add(UserId[i]);

Subject[i] = new LinkButton();
Subject[i].Font.Size = 20;
Subject[i].ID = "Subject" + i;
Subject[i].Style.Add("left", "600px");
Subject[i].Style.Add("position", "absolute");
Subject[i].Style.Add("top", H.ToString() + "px");
scroll.Controls.Add(Subject[i]);

Date[i] = new Label();
Date[i].Font.Size = 20;
Date[i].ID = "Date" + i;
Date[i].Style.Add("left", "900px");
Date[i].Style.Add("position", "absolute");
Date[i].Style.Add("top", H.ToString() + "px");
scroll.Controls.Add(Date[i]);

UserId[i].Text += read["ToUser"].ToString();
Subject[i].Text += read["Subject"].ToString();
Date[i].Text += read["SendDate"].ToString();
Time.Add(read["SendDate"].ToString());
Session["Time"] = Time;

UserId[i].Click += UserId_Click;
Subject[i].Click += Subject_Click;

delete[i] = new CheckBox();
delete[i].Font.Size = 20;
delete[i].ID = "delete" + i;
delete[i].Style.Add("left", "225px");
delete[i].Style.Add("position", "absolute");
delete[i].Style.Add("top", H.ToString() + "px");
scroll.Controls.Add(delete[i]);
delete[i].AutoPostBack = true;
delete[i].CheckedChanged += delete_Checked;

When a message is checked it will run through the event handler below, and call the method below

        protected void delete_Checked(object sender, EventArgs e)
        {
            CheckBox Checked = sender as CheckBox;
            Delete.MessagedChecked(Checked.Checked);
        }

and this code runs

       public void MessagedChecked(bool MessageChecked)
        {
            string MyConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

            connection.ConnectionString = (MyConnection);
            connection.Open();

            SqlCommand Checked = new SqlCommand(@"Update SentMessages Set Checked=@Checked", connection);

                if (MessageChecked == true)
                {
                    Checked.Parameters.AddWithValue("@Checked", true);
                }
                if (MessageChecked == false)
                {
                    Checked.Parameters.AddWithValue("@Checked", false);
                }

            Checked.ExecuteNonQuery();
        }

So basically When a check box is checked it shows that all of them are checked as true in the database, and I just want the box that is checked to show as true in the database not all of them unless there all checked.

Thanks and any help would be appreciated

implementing pessimistic concurrency using entity framework ?

How to get navigation prop from userManager.GetUser()?

$
0
0

In my Asp.net Core 2.0 app I have an ApplicationUser class where I store names and info. But I also have set a navigation property which is a class called "Company" there.

I use this in my controller to get the current user:

var person = await _userManager.GetUserAsync(User);

The problem is that the navigation property is not included in this(the other properties are however. person.Company is null). Is there a way to include it in this call or do I have to call the ApplicationUser table again after this?

What is the cleanest way to check if Money data type is null?

$
0
0

Greetings again.

I have several fieldnames as Money data type.

When users  attempt to insert records into the database, they are not required to enter values in all of the money fields.

To prevent the app from breaking with user clicks the submit button without entering any values in form fields that are of money type, I am using this:

                    if (checkAmt!= null)
                    {
                        if (string.IsNullOrEmpty(checkAmt))
                        {
                            checkAmt= "0";
                        }

This works. However, the issue here is that I have about 15 of those.

I will like to write a function with one argument (numeric or int or money), not sure what to use here.

So, let's say I have a function called:

private void CheckNull(int checkAmount)
{
  if (checkAmount!= null)
    {
      if (string.IsNullOrEmpty(checkAmount))
       {
        checkAmount= "0";
       }
    }
 }

Then I have, as stated before, about 12 to 15 form fields with money as data type in the db,  how do I call this function?

This is one of the 15 form fields"

cmd2.Parameters.Add("@checkAmt", SqlDbType.Money).Value = decimal.Parse(checkAmt); 

I tried this:

 cmd2.Parameters.Add("@checkAmt", SqlDbType.Money).Value = decimal.Parse(CheckNull(checkAmt));

It does not work.

Any ideas what I am doing wrong?

Viewing all 1698 articles
Browse latest View live