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

E-F code first database design: Choosing which model classes are part of the database, and which ones are not

$
0
0

When creating model classes in a project that is using code-first with E-F, does E-F only create database entities for classes that you have defined a DbSet for?  For example, if I had the following segment (assuming Picture, Album, and Picture_Album are all data model classes that I've defined as Public classes:

public DbSet<Picture> Pictures { get; set; }
public DbSet<Album> Albums { get; set; }
public List<Picture_Album> Pictures_Albums { get; set; }

E-F would only create tables for the Picture and Album classes, correct?  Since I defined DbSets for those classes, and it would ignore the Picture_album list (which that table would be used internally in memory and not need to be stored in the database as a table, since it's not defined with a DbSet.

I basically need to be able to create "view models" (like you find in MVC) for storing data in memory that does not need to be persisted/written to the database.  I'm also doing this mostly in code, and not using the EDMX designer/wizard (I don't think that matters though).


insert existing json in db

$
0
0

Hi,

My code:

var obj = new
        {
            data = new
        {
            post_info = new
            {
                ID = "1",
                UserId = HttpContext.Current.Request.Cookies["UserId"],
                date = DateTime.Now,
                imgpath = "none",
                videopath = "none",
                likecount = "1",
                sharecount = "1",
                likeperson = new { ID= "likeperson1" },
            },



        }

        };
             var post = JsonConvert.SerializeObject(obj);


             string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
             using (SqlConnection con = new SqlConnection(conStr))
             {
                 using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Posts VALUES(@Post)"))
                 {
                     cmd.CommandType = CommandType.Text;
                     cmd.Parameters.AddWithValue("@Post", post);
                     cmd.Connection = con;
                     con.Open();
                     cmd.ExecuteNonQuery();
                     con.Close();
                 }
             }


This code is on Button1 and insert correct.

In Button2 I need add another likeperson in db.  I need to find ID=1 and insert new likeperson:
likeperson = new { ID= "likeperson1" },
likeperson = new { ID= "likeperson2" }, - its new data-

Please help.

Additional information: User without permissions.

$
0
0

 private StockTicker(IHubConnectionContext<dynamic> clients)
    {
        Clients = clients;

        //Posts
        var mapper = new ModelToTableMapper<Posts>();
        mapper.AddMapping(s => s.ID, "ID");

        _tableDependency = new SqlTableDependency<Posts>(
            ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString,"tbl_Posts",
            mapper);

        _tableDependency.OnChanged += SqlTableDependency_Changed;
        _tableDependency.OnError += SqlTableDependency_OnError;
        _tableDependency.Start();
    }

Why I got this error? Additional information: User without permissions.

Context.SaveChanges() in foreach throwing "already an open data reader..." error

$
0
0


I have some c# code that looks something like this:

   using (var objContext = Entities.EntityUtils.GetSiteEntity(true))
      {
         var Articles = from art in objContext.v2_article
                        where ...SOME CONDITION IS MET...
                        select art;
         foreach (var Article in Articles)
         {
            bool bValueChanged = false;
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(Article.body);
            bValueChanged = FixNodes(ref htmlDoc, "//img", "src");
            bValueChanged = bValueChanged || FixNodes(ref htmlDoc, "//script", "src");
            bValueChanged = bValueChanged || FixNodes(ref htmlDoc, "//link", "href");
            if (bValueChanged)
            {
               Article.body = htmlDoc.DocumentNode.InnerHtml;

               objContext.SaveChanges();
            }
         }
       }

So, when it gets to the SaveChanges() link, I get an error that says there is already an open datareader... How do I do this kind of update?

SqlTableDependency_Changed what permission

$
0
0

Hi,

I have 2 database. One is from test with the same database: https://www.codeproject.com/Articles/1029976/SQL-Server-Notifications-on-Record-Change-with-Sig

void SqlTableDependency_Changed(object sender, RecordChangedEventArgs<Posts> e)
{
if (e.ChangeType != ChangeType.None)
{
BroadcastStockPrice(e.Entity);
}
}

and working exchange

I tried to use asp.net database with aspnet_membership with the same table tbl_posts and not working with the same example.

What permission I need?




two datareader relation between two tables

$
0
0

Hi,

I want to retrieve from second table commend under PostId.


var connectionString = ConfigurationManager.ConnectionStrings
                ["ConnectionString"].ConnectionString;
        using (var sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (var sqlCommand = sqlConnection.CreateCommand())
            {
                sqlCommand.CommandText = "SELECT * FROM [tbl_Posts] INNER JOIN tbl_UsersProfiles ON tbl_Posts.AuthorUserId = tbl_UsersProfiles.UserId WHERE DeletePost='false'";

                using (var sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        var ID = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("ID"));
                        var FullName = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Firstname"))+" "+ sqlDataReader.GetString(sqlDataReader.GetOrdinal("surname"));
                        var post = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Post"));
                        var DateByPost = sqlDataReader.GetDateTime(sqlDataReader.GetOrdinal("DateByPost"));
                        var imgcircle = (sqlDataReader.GetString(sqlDataReader.GetOrdinal("imgcircle")) == "/" ? "img/userimage.png" : sqlDataReader.GetString(sqlDataReader.GetOrdinal("imgcircle")));
                        var uplaodphoto = (sqlDataReader.GetString(sqlDataReader.GetOrdinal("uplaodphoto")) == "/" ? "none" : "img/"+sqlDataReader.GetString(sqlDataReader.GetOrdinal("uplaodphoto")));


                            using (var sqlConnection2 = new SqlConnection(connectionString))
                            {
                                sqlConnection2.Open();
                                using (var sqlCommand2 = sqlConnection2.CreateCommand())
                                {
                                    sqlCommand2.CommandText = "SELECT * FROM [tbl_PostComments] WHERE PostID='"+ID+"'";

                                    using (var sqlDataReader2 = sqlCommand2.ExecuteReader())
                                    {
                                        while (sqlDataReader2.Read())
                                        {
                                            var Message = (sqlDataReader2.GetString(sqlDataReader.GetOrdinal("Message")));

                                        }
                                    }
                                }
                            }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Stock
/// </summary>
public class Posts
{
    public int ID { get; set; }

    public string FullName { get; set; }

    public string Post { get; set; }

    public DateTime DateByPost { get; set; }

    public string replies { get; set; }

    public string imgcircle { get; set; }

    public string uplaodphoto { get; set; }

    public string Message { get; set; }

}



Message I need to get if I have from first table tbl_Posts ID=2

and second table tbl_PostComments.PostId I have two comments under PostId=2

Message, PostId
test1, 2
test5, 2
test6, 5


Then I need to get two comment in my case.

How can I resolved this?



Does loading SqlDataReader data into object is possible in c#

$
0
0

Hi All,

I want to know does loading SqlDataReader data into "default" object is possible? If yes, then how to make the code below to work.

The code doesn't give any error but showing no data. 

        private object dtData()
        {

            object obj = new object();

            string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connstring))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT ChildId, [Name], [Password], [DateOfBirth] FROM ChildInformation", conn))
                {
                    conn.Open();

                    SqlDataReader reader = cmd.ExecuteReader();

                    obj = (object)reader;
                }
            }

            return obj;
        }

Thanks

nvalid column name 'Home_Id'. - CODE FIRST MANY TO MANY RELATIONSHIP in asp.net mvc5

$
0
0

This is the code im working with , and im trying to build many to many relationship between Home and Event tables , but im getting this result :


http://localhost:49477/Homes/Index

CREATE TABLE [dbo].[Events] (    [Id]                NVARCHAR (128) NOT NULL,    [Image]             NVARCHAR (MAX) NULL,    [InsertDate]        DATETIME       NULL,    [PublishDate]       DATETIME       NULL,    [ExpiryDate]        DATETIME       NULL,    [ShortDescription1] NVARCHAR (MAX) NULL,    CONSTRAINT [PK_dbo.Events] PRIMARY KEY CLUSTERED ([Id] ASC));


CREATE TABLE [dbo].[Homes] (    [Id]            NVARCHAR (128) NOT NULL,    [LocationID]    NVARCHAR (128) NULL,    [EventID]       NVARCHAR (128) NULL,    [HappyHourID]   NVARCHAR (128) NULL,    [Description]   NVARCHAR (MAX) NULL,    [FacebookLink]  NVARCHAR (MAX) NULL,    [InstagramLink] NVARCHAR (MAX) NULL,    CONSTRAINT [PK_dbo.Homes] PRIMARY KEY CLUSTERED ([Id] ASC),    CONSTRAINT [FK_Homes_Events] FOREIGN KEY ([EventID]) REFERENCES [dbo].[Events] ([Id]),    CONSTRAINT [FK_Homes_HappyHours] FOREIGN KEY ([HappyHourID]) REFERENCES [dbo].[HappyHours] ([Id]),    CONSTRAINT [FK_Homes_Locations] FOREIGN KEY ([LocationID]) REFERENCES [dbo].[Locations] ([Id]));


Server Error in '/' Application.


Invalid column name 'Home_Id'.
Invalid column name 'Event_Id'.

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 'Home_Id'.
Invalid column name 'Event_Id'.

Source Error: 

Line 37:
Line 38:             var homes = db.Homes.Include(h => h.Event).Include(h => h.HappyHour).Include(h => h.Location);Line 39:             return View(homes.ToList());Line 40:
Line 41: 


Source File: S:\CodeRepository\drenusha_gjurka\CoffeeBarRestaurantMVC\CoffeeBarRestaurantMVC\Controllers\HomesController.cs    Line: 39 

Stack Trace: 

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CoffeeBarRestaurantMVC.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CoffeeBarRestaurantMVC;

namespace CoffeeBarRestaurantMVC.Controllers
{
    public class HomesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Homes
        public ActionResult Index()
        {

            var homes = db.Homes.Include(h => h.Event).Include(h => h.HappyHour).Include(h => h.Location);
            return View(homes.ToList());


        }

        // GET: Homes/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Home home = db.Homes.Find(id);
            if (home == null)
            {
                return HttpNotFound();
            }
            return View(home);
        }

        // GET: Homes/Create
        public ActionResult Create()
        {


            ViewBag.EventID = new SelectList(db.Events, "Id", "ShortDescription1");
            ViewBag.HappyHourID = new SelectList(db.HappyHours, "Id", "ShortDescription1");
            ViewBag.LocationID = new SelectList(db.Locations, "Id", "Name");
            return View();
        }

        // POST: Homes/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,LocationID,EventID,HappyHourID,Description,FacebookLink,InstagramLink")] Home home)
        {
            if (ModelState.IsValid)
            {
                db.Homes.Add(home);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.EventID = new SelectList(db.Events, "Id", "ShortDescription1", home.EventID);
            ViewBag.HappyHourID = new SelectList(db.HappyHours, "Id", "ShortDescription1", home.HappyHourID);
            ViewBag.LocationID = new SelectList(db.Locations, "Id", "Name", home.LocationID);
            return View(home);
        }

        // GET: Homes/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Home home = db.Homes.Find(id);
            if (home == null)
            {
                return HttpNotFound();
            }
            ViewBag.EventID = new SelectList(db.Events, "Id", "ShortDescription1", home.EventID);
            ViewBag.HappyHourID = new SelectList(db.HappyHours, "Id", "ShortDescription1", home.HappyHourID);
            ViewBag.LocationID = new SelectList(db.Locations, "Id", "Name", home.LocationID);
            return View(home);
        }

        // POST: Homes/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,LocationID,EventID,HappyHourID,Description,FacebookLink,InstagramLink")] Home home)
        {
            if (ModelState.IsValid)
            {
                db.Entry(home).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.EventID = new SelectList(db.Events, "Id", "ShortDescription1", home.EventID);
            ViewBag.HappyHourID = new SelectList(db.HappyHours, "Id", "ShortDescription1", home.HappyHourID);
            ViewBag.LocationID = new SelectList(db.Locations, "Id", "Name", home.LocationID);
            return View(home);
        }

        // GET: Homes/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Home home = db.Homes.Find(id);
            if (home == null)
            {
                return HttpNotFound();
            }
            return View(home);
        }

        // POST: Homes/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Home home = db.Homes.Find(id);
            db.Homes.Remove(home);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}




































@model IEnumerable<CoffeeBarRestaurantMVC.Models.Home>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}<h2>Index</h2><p>
    @Html.ActionLink("Create New", "Create")</p><table class="table"><tr><th>
            @Html.DisplayNameFor(model => model.Id)</th><th>
            @Html.DisplayNameFor(model => model.Event.Id)</th><th>
            @Html.DisplayNameFor(model => model.HappyHour.Id)</th><th>
            @Html.DisplayNameFor(model => model.Event.ShortDescription1)</th><th>
            @Html.DisplayNameFor(model => model.HappyHour.ShortDescription1)</th><th>
            @Html.DisplayNameFor(model => model.Location.Name)</th><th>
            @Html.DisplayNameFor(model => model.Description)</th><th>
            @Html.DisplayNameFor(model => model.FacebookLink)</th><th>
            @Html.DisplayNameFor(model => model.InstagramLink)</th><th></th></tr>

@foreach (var item in Model) {
    <tr><td>
            @Html.DisplayFor(modelItem => item.Id)</td><td>
            @Html.DisplayFor(modelItem => item.Event.Id)</td><td>
            @Html.DisplayFor(modelItem => item.HappyHour.Id)</td><td>
            @Html.DisplayFor(modelItem => item.Event.ShortDescription1)</td><td>
            @Html.DisplayFor(modelItem => item.HappyHour.ShortDescription1)</td><td>
            @Html.DisplayFor(modelItem => item.Location.Name)</td><td>
            @Html.DisplayFor(modelItem => item.Description)</td><td>
            @Html.DisplayFor(modelItem => item.FacebookLink)</td><td>
            @Html.DisplayFor(modelItem => item.InstagramLink)</td><td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })</td></tr>
}</table>
using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Web;namespace CoffeeBarRestaurantMVC.Models
{    public class Home    {        public Home()        {            this.Events = new HashSet<Event>();    //        this.Locations = new HashSet<Location>();      //      this.HappyHours = new HashSet<HappyHour>();        }        public string Id { getset; }        public string LocationID { getset; }        public string EventID { getset; }        public string HappyHourID { getset; }        public string Description { getset; }        public string FacebookLink { getset; }        public string InstagramLink { getset; }        public virtual Event Event { getset; }        public virtual Location Location { getset; }        public virtual HappyHour HappyHour { getset; }               public virtual ICollection<Event> Events { getset; }      //  public virtual ICollection<Location> Locations { get; set; }    //    public virtual ICollection<HappyHour> HappyHours { get; set; }    }
}

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Web;namespace CoffeeBarRestaurantMVC.Models
{    public class Event    {        public Event()        {            this.Homes = new HashSet<Home>();            //        this.Locations = new HashSet<Location>();            //      this.HappyHours = new HashSet<HappyHour>();        }        public string Id { getset; }        public string Image { getset; }        public Nullable<System.DateTime> InsertDate { getset; }        public Nullable<System.DateTime> PublishDate { getset; }        public Nullable<System.DateTime> ExpiryDate { getset; }        public string ShortDescription1 { getset; }  //      [ForeignKey("Home")]     //   public string HomeID { get; set; }        //  public string HomeId { get; set; }    //    [InverseProperty("Homes")]  //      public virtual Home Home { get; set; }       public virtual ICollection<Home> Homes { getset; }    }
}

How to convert a query to lambda based

$
0
0
var usersWithRoles = (from user in context.Users
                                  select new
                                  {
                                      UserId = user.Id,
                                      Username = user.UserName,
                                      Email = user.Email,
                                      RoleNames = (from userRole in user.Roles
                                                   join role in context.Roles on userRole.RoleId
                                                   equals role.Id
                                                   select role.Name).ToList()
                                  }).ToList().Select(p => new Users_in_Role_ViewModel()

                                  {
                                      UserId = p.UserId,
                                      Username = p.Username,
                                      Email = p.Email,
                                      Role = string.Join(",", p.RoleNames)
                                  });  

guide me how could i compose the above query using lambda if possible. thanks

How to fetch master detail data using EF and LINQ

$
0
0

suppose i have a order and order detail entity. i want to fetch specific order data and its related order detail by EF.

can i use this LINQ query

IEnumerable<Order> order= _ctx.order
            .Include(x => x.orderdetails)
            .Where(x => x.OrderID== _OrderID).ToList();

does the above code works fine? also tell me how to achieve the same with join also?

also tell me if i need to show specific customer data and customer order and order details then how i need to compose my EF query? help me with code. thanks

EF left or right join

$
0
0

see the query

var answer = (from c in db.customers
              join p in db.purchases
              on c.ID = p.CustomerID into subs
              from sub in subs.DefaultIfEmpty()
              group sub by new { c.ID, c.Name } into gr
              select new {
                  gr.Key.ID,
                  gr.Key.Name,
                  Total = gr.Count(x => x != null),
                  CountCompleted = gr.Count(x => x != null && x.CompletedTransaction)
              }).ToList();

the above join is left or right join?

i got the above join hint from these url

https://stackoverflow.com/a/8055893/6188148
https://stackoverflow.com/a/46947013/6188148

how to determine what kind of join is it ?

thanks

How to show customer data and order count using LINQ

$
0
0

my table structures are

Customer
----------
CustomerID
FirstName
LastName
PhoneNo
Email

Order
--------
CustomerID
OrderID
OrderStatus
OrderDate
TotalPrice

OrderDetails
------------
ID
OrderID
ProductID
Qty

so now i have to show CustomerID,FirstName,LastName,PhoneNo,Email and OrderCount

please give me a sample EF linq query

thanks

How to save single entity/class data to multiple table

$
0
0

so tell me how could i design whole things. suppose i have a registration class what has so many properties like

Account information
----------------------
First Name
Surname
Company Name
Contact Number
Email :
Password
Confirm Password

Billing information
----------------------
Address1
Address2
Town/City
County/State
PostCode
Billing Country

i have one customer class which has many properties for account and billing information. now i want when i will save customer data by EF then account info will be saved in customer table and billing info will be saved in address table. so tell me how could i do this mapping when i am working with EF db first and code first.

i found one relevant article link https://dukhabandhu.wordpress.com/2014/11/12/table-and-entity-splitting-in-entity-framework-code-first/

https://blogs.msdn.microsoft.com/simonince/2009/03/23/mapping-two-tables-to-one-entity-in-the-entity-framework/

i think this link is close to my requirement https://dotnetfalcon.azurewebsites.net/stackoverflow-adventures-entity-framework-code-first-advanced-mapping-scenarios/

they are showing that we must have two class having parent-child relationship then we can save to multiple table.

please discuss with a sample code. thanks

Error, " Cannot open database "BrentPractice" requested by the login. The login failed. Login failed for user 'rnalC

$
0
0

How do I fix my code where I can open the database? Here is my code:

public int InsertCommand(int logId, string edi, string personFormalName, DateTime activityDateTime, string activityTypeDescriptor, string additionalDetails, string reasonMessage, string notes)
        {
            string connectionString = "Data Source=Bill\\Bill;Initial Catalog=Billy;Integrated Security=True";
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                string strCommand = "Insert INTO Tracker(id, edi, personsName, date, descriptor, details, reasons, notes)";
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strCommand;
                cmd.Connection = conn;conn.Open(); // <-----------------------------------------error here                cmd.Parameters.AddWithValue("@id", logId);
                cmd.Parameters.AddWithValue("@edi", edi);
                cmd.Parameters.AddWithValue("@personName", personFormalName);
                cmd.Parameters.AddWithValue("@date", activityDateTime);
                cmd.Parameters.AddWithValue("@descriptor", activityTypeDescriptor);
                cmd.Parameters.AddWithValue("@details", additionalDetails);
                cmd.Parameters.AddWithValue("@reasons", reasonMessage);
                cmd.Parameters.AddWithValue("@notes", notes);

                return cmd.ExecuteNonQuery();
            }
            catch
            {
                throw;
            }

Linq Update List marking duplicates based of a columns in the list .

$
0
0

Goal:  I am sure there is a better way of doing this and would appreciate this learning opportunity.

I have a list of  products  and  want to find all duplicate products in the list,   then mark the status field in the list  with -1 to signal duplicate record found. This is based on two or more columns in the list currently I have three columns but would like to build a helper on the the columns that  them as duplicate. The rules are to check by Name, Category and Weight if there are duplicates in the list mark the Status field with -1 for the duplicate record.  (

The following code works correctly and returns the correct result, but I feel there are other cleaner way of doing this than my code. I welcome any and all suggestions.

Currently it is hard coded to work with this example but I am confident this could be done with a helper or extension method that would be more generic and useful. 

public class Product
{
    public string Name { get; set; }
    public string Category { get; set; }
    public char Weight { get; set; }
    public int Status { get; set; }
	public string Location {get;set;}
}

public enum ImportStatus
{
    Duplicate = -1,
    AwaitingProcess = 0,
}

void Main()
{

     // you need to fix the case sensitivity
	 // *** Attention ***
	List<Product> ProductList = new List<Product>()
	{
	 new Product(){Name="Ginger",Category="Fresh", Weight=	'B',Status=  0, Location="Produce"}
	,new Product(){Name="Ginger",Category="Dry",   Weight=	'A',Status=  0, Location="Front Counter"}
	,new Product(){Name="LEMON",Category="Fruit",   Weight=	'B',Status=  0, Location="Name Area"}
	,new Product(){Name="LEMON",Category="Fruit",   Weight=	'B',Status=  0, Location="Outer Court"}
	,new Product(){Name="lettuce",Category="Produce", Weight='X',Status=  0, Location="Produce"}
	,new Product(){Name="Lettuce",Category="Product", Weight='X',Status=  0, Location="Freezer"}
	,new Product(){Name="Apple",Category="Fruit",   Weight=	'S',Status=  0, Location="Product"}
	,new Product(){Name="Pine Apple",Category="Fruit", Weight=	'S',Status=  0, Location="Front Counter"}
	};


	List<Product> filteredProductList  =ProductList
	.Where (l => l.Status==0)
	.GroupBy (r=>new { r.Name,r.Category,r.Weight},( grp, tbl)=> new{GROUP=grp,TBL=tbl})
	.Where (r => r.TBL.Count()>1)
	.SelectMany(r=>r.TBL)
	.Select(r=>new Product { Name=r.Name,Category=r.Category,Weight= r.Weight,Location=r.Location,Status=(int)ImportStatus.Duplicate})
	.Union(ProductList
	.Where (l => l.Status==0)
	.GroupBy (r=>new  { r.Name,r.Category,r.Weight},( grp, tbl)=> new{GROUP=grp,TBL=tbl})
	.Where (r => r.TBL.Count()==1)
	.SelectMany(r=>r.TBL)
	.Select (r =>new Product{ Name=r.Name,Category=r.Category,Weight= r.Weight,Location=r.Location,Status=0})
	)

Here is the desired output

<div id="final"> <div class="spacer">
NameCategoryWeightStatusΞΞLocation
LEMONFruitB-1Name Area
LEMONFruitB-1Outer Court
GingerFreshB0Produce
GingerDryA0Front Counter
lettuceProduceX0Produce
LettuceProductX0Freezer
AppleFruitS0Product
Pine AppleFruitS0Front Counter
</div> </div>



Error openning a connection

$
0
0

Here is the error: A connection was successfully established with the server, but then an error occurred during the login process, error 0, No process is on the other end of the pipe. What cause this error and how do I fix it?

SQL Server 2016

Visual Studio 2017

Here is my connection string:

string connectionString = @"Data Source=BRENTHUMBER\BRENT;Initial Catalog=BrentPractice;Integrated Security=False";
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                string strCommand = "Insert INTO Tracker(id, edi, personsName, date, descriptor, details, reasons, notes)";
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strCommand;
                cmd.Connection = conn;
                conn.Open(); // <-----------------------------------------error here

Store the Controllers name and Actions Name into my Custom Tables that I Add them into Identity in CodeFirst Asp.Net MVC Project

$
0
0

Seniors, <br/>
I'm using ASP.NET Identity on my ASP.Net web application and I Add my custom Tables(with their relations) to Identity on myCodeFirst ASP.Net MVC Project.when I Run Project for the first time,the databace is created automatically with the custom tables and relations between them in SqlServer. <br/>
Custom Tables :

1. MvcControllers
2. ActionsTbls
3. GroupsTbls
4. AspNetUser_Action
5. AspNetUser_Group
6. Action_Group

* This is The Diagram of my Database Image :Database Diagram Click Here

For Creating Custom tables,I Add Some Codes to IdentityModels.cs. <br/>
IdentityModels.cs :

namespace Admin_Base_SN.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public virtual AspNetUser_Action AspNetUser_Action { get; set; }

public virtual AspNetUser_Group AspNetUser_Group { get; set; }

}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{


public DbSet<MvcController> MvcController { get; set; }
public DbSet<ActionsTbls> ActionsTbls { get; set; }
public DbSet<AspNetUser_Action> AspNetUser_Actions { get; set; }

public DbSet<GroupsTbl> GroupsTbls { get; set; }
public DbSet<Action_Group> Action_Groups { get; set; }

public DbSet<AspNetUser_Group> AspNetUser_Groups { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}

public static ApplicationDbContext Create()
{
return new ApplicationDbContext();

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

// one-to-zero or one relationship between ApplicationUser and Customer
// UserId column in Customers table will be foreign key
modelBuilder.Entity<ApplicationUser>()
.HasOptional(m => m.AspNetUser_Action)
.WithRequired(m => m.ApplicationUser)
.Map(p => p.MapKey("AspNetUser_Id"));

modelBuilder.Entity<ApplicationUser>()
.HasOptional(m => m.AspNetUser_Group)
.WithRequired(m => m.ApplicationUser)
.Map(p => p.MapKey("AspNetUser_Id"));

}

}
}


What I want <br/>
At first,I want to save All the Controllers Names and Actions Names of Project into separated Lists,then insert them into MvcController Table & ActionsTbl Table.This process should be done automatically when I Run Project for the first time.I mean When the Database is Created, the Lists inert to their tables automatically.

* I think it's better to Add a New Custom Function to the Identity for inserting Lists to the Tables.

I appreciate your efforts in reaching a solution for my problem.

Entity framework acces by reference

$
0
0

how to reference to properties of entitiy framework models?

ReferenceTest(EntityModel.Adress)

sub ReferenceTest(t as property)

msgbox(t)

end sub

entity framework acces by string name

$
0
0

hi.

how do i acces an model's column name by string?

such as

myrowmodel.column("id)) = "465746"

myrowmodel.column("food)) = "fish"

and how do i convert it back to string?

dim str as string = myrowmodel.id.tostring

Can not migrate Database

$
0
0

Hello. I don't know how to just ask the question.

When I run update-database, a database is created. However, without the table __Migrations (or whatever its name was). The database is up-to-date.
When I then execute update database, the above table is created. but has only the first entry. I think because the update stopped there. Who can help?

 public async Task SeedAsync()
        {

            if (!DBContext.Database.EnsureCreated())
                DBContext.Database.Migrate();

        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DataService seeder)
        {
            loggerFactory.AddFile("Logs/myapp-{Date}.txt");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();


            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            // here you can see we make sure it doesn't start with /api, if it does,
            // it'll 404 within .NET if it can't be found
            app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
            {
                builder.UseMvc(routes =>
                {
                    routes.MapSpaFallbackRoute(
                        name: "spa-fallback",
                        defaults: new { controller = "Home", action = "Index" });
                });
            });


            seeder.SeedAsync().Wait();
        }

Viewing all 1698 articles
Browse latest View live


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