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

Composite index in efcore 2.0

$
0
0

I have two models, model A contains one or more of Model B. Model B has a property, name, which must be unique only per model A.

modelBuilder.Entity<ModelB>()
    .HasIndex(m => new {m.ModelAId, m.Name})
    .IsUnique();

This does not produce the desired composite index, but rather two, a unique on Name and non-unique on fk. How can I accomplish this?

Thanks!


How to add 2 foreign keys and their corresponding navigation properties to a model

$
0
0

Hi all

I a newcomer in asp.net mvc and i got stuck with a trivial problem for hours. I have a simple class that models a message. its here:

publicclassMessage{[Key]publicintId{ get;set;}// AspNetUserspublicApplicationUserSender{ get;set;}publicApplicationUserReceiver{ get;set;}// SenderId of the message[Required][ForeignKey("Sender")][Display(Name="Sender")][InverseProperty("MessageSenderId")]publicstringSenderId{ get;set;}// ReceiverId of this message[Required][ForeignKey("Receiver")][Display(Name="Receiver")][InverseProperty("MessageReceiverId")]publicstringReceiverId{ get;set;}// other properties}

The SenderId and ReceiverId are the Id of sender and receiver of this message respectively. The Sender and Receiver are navigation properties to fetch them from database when i want to pass the message model to view.

Unfortunately, when i want to add a new migration, this error is raised: The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Mails_dbo.AspNetUsers_ReceiverId". The conflict occurred in database "DbName", table "dbo.AspNetUsers", column 'Id'.

What can i do? Thanks

why not to create table __efmigrationshistory for mysql

$
0
0

I am using asp.net core 2.0  + entity framework core to create new project, the database is mysql. when I run the project and then it can automatically create an new database, but it create the table "__efmigrationshistory".  

How reduce result set to every nth row

$
0
0

Hi, for a certain query I can get up to a couple of millions of rows in form of time series data. These rows need to be display on a screen with a limited amout of pixels so it makes sense toblur them or in other words to only select every nth row of the original set. Using SQL I'd do something like this (source stackoverflow)

SELECT t.id, t.key
FROM
(
    SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum
    FROM datatable
) AS t
WHERE t.rownum % n = 0
ORDER BY t.key

The problem is, I would like to do this with LINQ but I just can't figure out how. A methodROW_NUMBER is not known and using an index in the where clause gives me an error.

Query.Where((s, i) => i % n == 0);

Edit: more precisely

Query.Select((s, i) => new { index = i, data = s } ).Where(s => s.index % n == 0).Select(s => s.data)

The only solutions that worked for me so far is to temporarily run the SQL (toList) and filter it afterwards. This however slows down my server significantly. 

EF returning two identical records when 2 different records are in the table.

$
0
0

I have this method in my Music Entities class:

publicstaticList<Music> getMusic( decimal id, IDataProvider db )
{
  List<Music> data = db.MusicData.Where( m => m.id == id ).ToList<Music>();
 return data;
}

There are only 2 records in the database both with the same id field.

But this code returns two copes of the first of the two records.

How can I get all records for this id number?

 

 

Multiple Relationships/Foreign Keys Between Two Tables (in Classes)

$
0
0

Hi friends,

I seek to create two tables, in shape of classes, via migrations. One with general info about the Employees:

  • Employee_ID (PK)
  • Employee_Name

and another tabe about their activities in passing a transaction with their supervisors, consisting fields like:

  • Activity_ID (PK)
  • Activity_DateTime
  • Activity_Result (A boolean value like Pass/Fail)
  • Main_Employee (FK)
  • Assistant (FK)
  • Supervisor (FK)

With the three last fields of the second table sought to be foreign keys, i.e. the Employee himself, his Assistant & his Supervisor, linked with the same table of Employees, what would be the correct way of representing in the two classes?

Being a novice in this regard, I am confused as to how should I set up more than one relationship between two same tables but different fields.

Googling has led me to find only single relationships.

Please see if any of you experts can help in this regard. Any special data annotations?

Thanks in advance.

Trouble with date formats & conversions as part of parameterised query

$
0
0

Hi all,

I am sure this is a simple one, but I have given myself a headache trying to sort it out. Can someone point me in the right direction!?

I have a VB.net intranet page with a couple of datapickers, the selected values of which are passed into a sql query to return data for a gridview on the page.

It all works perfectly - except for the fact that the datepicker returns the formatYYYY-MM-DD, but the SQL query is reading it as YYYY-DD-MM. So anything later than the 12th day of the month errors, and obviously the wrong date range is being returned regardless.

This is the sub that's setting the parameters and firing off the stored procedure.

---------------------------------------

Protected Sub Refresh2_click(sender As Object, e As EventArgs) Handles Me.Load

Dim constr As String = ConfigurationManager.ConnectionStrings("constr3").ConnectionString
Using conn As New SqlConnection(constr)
conn.Open()
Dim exec As SqlCommand = New SqlCommand("MAXP030inrt.dbo.uspUjbotif", conn)
exec.Parameters.AddWithValue("@DateFrom", datepicker1.value)
exec.Parameters.AddWithValue("@DateTo", datepicker2.value)
exec.Parameters.AddWithValue("@Customer", "%" & ddlCustomer.text & "%")
exec.Parameters.AddWithValue("@ProdGrp", "%" & ddlProdGrp.text & "%")
exec.CommandType = CommandType.StoredProcedure
exec.ExecuteReader()
End Using

End Sub

-------------------------------------

This is the pertinent part of the SQL stored procedure:

--------------------------------------

where
a.[oemer_reqdate] >= @DateFrom AND a.[oemer_reqdate] <= @DateTo

--------------------------------------

I'm struggling to identify where to put a conversion, and what that conversion would look like.

Any help!? TIA

JB

(Reason for edits: formatting issues!)

Store Linq statement in the database

$
0
0

Is it possible to write a linq statement, store it in the database and then have Entity Framework read that in and process it via Entity Framework?

We are currently running normal sql statements in the database, but it is VERY slow on large queries. 


see SQL query with variables filled in (produced by LINQ QUERY)

$
0
0

How can i see the actual SQL query that is run on the SQL server with all variables filled in?

i am using entity framework

var DataExp = weblicensedb.FeatureDatas.Where(fd => fd.LicenseID == id);

thank you for your help.

need help with linq to sql, and a navigation object

$
0
0

Hi

I have an entity model which has a navigation property to a list of another entity model

something like

ModelA
{
   public List<ModelB> ModelB {get;set;}
}

ModelB
{
   public DateTime DateAdded {get;set;}
public string Name {get;set;}


}

now ModelB can have anyhting in the name, however the important record is the newest

So i want to be able to select all ModelA's which have only the newest records in ModelB's has a name of "Foo".

I would normally use ModelA.Any(b => b.Name == foo).ToList()

however this will do all the records and not just the newest.

the date added will vary and some will have no records at all

Any help would be appriciated

>= DateTime.Today no results problem

$
0
0

When i am adding  the following to the linq query the are no results returned, whithout the selector it does return results.

.Where(fd => fd.ProtectData.ExpirationDate >= DateTime.Today)

When i am using SQL in the management console  it doe sreutn results.
Where CRMcompanyID = 2542 AND ExpirationMode = 'EXPIRING' AND ExpirationDate >= GETDATE()

any ideas , what might go wrong here ?

 IQueryable<string> FeatureDataExpiring = weblicensedb.FeatureDatas  // source
              .Join(weblicensedb.ProtectDatas,         //target
              fd => fd.ProtectID,                      //FK
              pd => pd.ProtectID,                      //PK
              (fd, pd) => new { FeatureData = fd, ProtectData = pd }).Where(fd => fd.ProtectData.Deleted == 0).Where(fd => fd.ProtectData.CRMcompanyID == CompanyID).Where(fd => fd.ProtectData.ExpirationMode == "EXPIRING").Where(fd => fd.ProtectData.ExpirationDate >= DateTime.Today)  // result
              .Select(x => x.FeatureData.LicenseString); // select result

need help with expressions and or instead of and

$
0
0

hi

In my service layer i use this to build and IQueryString

var queryList = new List<Expression<Func<SomeEntity, bool>>>();

            queryList.Add(a => a.NavpropId == someId);
            queryList.Add(b => b.NavB.Any(bc => bc.SomeProperty == searchString));

Then in the repositoy I use

 if (predicates != null)
            {
                foreach (var item in predicates)
                {
                    query = query.Where(item);
                }

            }

And i really like it, it makes it easy to manage and understand my queries.

However in doing this the seperate satements are all"and" (eg someId and someSearchString)

However I would also like to use a similar pattern to build a statement that also has an or part of the query

Does anyone have any ideas, any suggestions would be appriciated.

(the main reasoning behind this, is I want to allow a user to enter a search string, then i want to use that string to search multiple fields)

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

$
0
0

i m facing below error

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The entity or complex type 'CallCenterModel.TBL_CustomerMaster' cannot be constructed in a LINQ to Entities query.

i have below function  where error /exception occured and TBL_CustomerMaster is auto generated class

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CallCenterCRM
{
    using System;
    using System.Collections.Generic;

    public partial class TBL_CustomerMaster
    {
        public int CustomerId { get; set; }
        public string Cus_Name { get; set; }
        public System.DateTime ? Cus_RegDate { get; set; }
        public System.DateTime ?  Cus_RegExpDate { get; set; }
        public string Cust_Address { get; set; }
        public string Cus_Email { get; set; }
    }
}

  public List<TBL_CustomerMaster> GetCustomerByID(int Customerid)
    {

        var results = (from p in db.TBL_CustomerMaster

                       where p.CustomerId == Customerid

                       select new TBL_CustomerMaster

                       {
                           Cus_Name = p.Cus_Name,
                           Cust_Address = p.Cust_Address,
                           Cus_Email = p.Cus_Email


                           //  prefix = pi.prefix,



                       }).ToList();
        return results;

    }

please note down i m using EF 6 and MVC 5

Populating Collection property in a Class

$
0
0

I was wondering what is best practice for populating a collection property of a Class using liq to sql. Thanks !

Building dynamic Linq to SQL statements for the entity framework Lamda

$
0
0

Hi

Up until now I am building an asp.net mvc application using the entity framework, and until now I have only needed a fairly simple set of where statements to do everything i need.

However I now need to perform more complex search using alot more "or" statements instead of all the "and" statements

So i need to start building more dynamic statements

I am currently using expression to loop into a where clause

What i am interested in, is whats considered the current best way to achive more dynamic linq to sql statements?

Links to tutorials would be appriciated but any suggestes would also be appriciated.


auto validation error

$
0
0

i m working in EF 6 and MVC 5

i find below error  highlighted in red ,though i did not specified any where in application. let me share view model and db script and other piece of code

The field HoldiayDate must be a date.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CallCenterCRM
{
    using System;
    using System.Collections.Generic;

    public partial class TBL_Holiday
    {
        public int HolidayId { get; set; }
        public Nullable<System.DateTime> HoldiayDate { get; set; }
        public string ReasonforHoliday { get; set; }
        public Nullable<int> Empscrutinize { get; set; }
    }
}
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace CallCenterCRM.Models
{
    public class EmpHolidayViewModel
    {
        [HiddenInput(DisplayValue = true)]
        [Key]
        public int HolidayId { get; set; }
        public System.DateTime ? HoldiayDate { get; set; }
        public string ReasonforHoliday { get; set; }

        public int ? Empscrutinize { get; set; }

       // public String SelectedEmployee { get; set; }
        public IEnumerable<SelectListItem> Employees { get; set; }


    }
}
@model CallCenterCRM.Models.EmpHolidayViewModel<script type="text/javascript">$(function(){$("#HoldiayDate").datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: 'dd.mm.yy'

		});
	});
</script>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()<div class="form-horizontal"><h4>EmpHolidayViewModel</h4><hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })<div class="form-group">
            @Html.LabelFor(model => model.HoldiayDate, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.HoldiayDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.HoldiayDate, "", new { @class = "text-danger" })</div></div><div class="form-group">
            @Html.LabelFor(model => model.ReasonforHoliday, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.ReasonforHoliday, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ReasonforHoliday, "", new { @class = "text-danger" })</div></div><div class="form-group">
            @Html.LabelFor(model => model.Empscrutinize, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.DropDownListFor(model => Model.Empscrutinize, new SelectList(Model.Employees, "Value", "Text"), "..Select..", htmlAttributes: new { @class = "form-control", id = "Employee" })


                @Html.ValidationMessageFor(model => model.Employees, "", new { @class = "text-danger" })</div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Create" class="btn btn-default" /></div></div></div>
}<div>
    @Html.ActionLink("Back to List", "Index")</div>

USE [CallCenter]
GO

/****** Object: Table [dbo].[TBL_Holiday] Script Date: 02/15/2018 17:00:45 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TBL_Holiday](
[HolidayId] [int] IDENTITY(1,1) NOT NULL,
[HoldiayDate] [datetime] NULL,
[ReasonforHoliday] [varchar](50) NULL,
[Empscrutinize] [int] NULL,
CONSTRAINT [PK_TBL_Holiday] PRIMARY KEY CLUSTERED
(
[HolidayId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Best way to implement entity framework

$
0
0

I have been struggling to find the best way of implementing entity framework Database first for CRUD operations on a large application.
There are about hundreds of tables and stored procedures in the database, I would need to build a Data Access Layer implementing entity framework
which would be robust, maintainable, extensible and testable.

I have gone through many urls trying to find the best approach.Found few links below implementing the basic functionality
but I guess they are not testable as the DbContext is called in the controller or console application. Probably
not suited for large applications

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/database-first-development/
https://msdn.microsoft.com/en-us/library/jj200620(v=vs.113).aspx
http://www.c-sharpcorner.com/article/working-with-entity-framework-using-database-first-approach/
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm
https://www.codeproject.com/Tips/869553/CRUD-operation-with-Entity-Framework-Database-Fi

Then I found few approaches using Generic repository and unit of work pattern
https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
http://www.janholinka.net/Blog/Article/9
http://rahulrajatsingh.com/2014/06/understanding-repository-and-unit-of-work-pattern-and-implementing-generic-repository-in-asp-net-mvc-using-entity-framework/

But then again, there are suggestions by experts that Entity framework implements Repository and Unit of Work by default and should only use if the ORM is going to get changed later.
If that's true, in my case ORM does not going to get changed.
Some others suggest that IDbContext should be used as opposed to DbContext for testability.

From all the research I did, I understood that I should use Repository and Unit of Work pattern with IDbContext.
There are many approaches again on it and all of them without using IDbContext.
If my approach is correct, could anyone please suggest a sample code where I can find an easiest way of implementing
Repository and Unit Of Work Pattern with IDbContext.

If my approach is outdated and there are best approaches in the market, could anyone please point me in the right direction with an example code

Must declare the scalar variable "@UserName".

$
0
0

Hi,

I am having this error :

Must declare the scalar variable "@UserName".

my aspx page 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10"><Columns><asp:BoundField ItemStyle-Width="150px" DataField="Order_Name" HeaderText="Order_Name" /><asp:BoundField ItemStyle-Width="150px" DataField="Date" HeaderText="Date" /><asp:BoundField ItemStyle-Width="150px" DataField="Order#" HeaderText="Order#" /><asp:BoundField ItemStyle-Width="150px" DataField="Status" HeaderText="Status" /></Columns></asp:GridView>


 and my cs is

   protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserName"] = HttpContext.Current.User.Identity.Name;
        if (!this.IsPostBack)
        {
            this.BindGrid();
        }
    }

   
    private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["urConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Order_Name, Date, Order#, Status FROM DB_120 WHERE UserName= @UserName"))

           
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }
    }

    protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        this.BindGrid();
    }
}

Can anyone help me in this please.

How to ON UPDATE CASCADE

$
0
0

Is there any example for a Code First approach on ASP Core for allowing one to edit theID of a Parent Table (the Primary Key) and auto updating the relevant Foreign Keys wherever used in other tables? CRUD isn't allowing me to update a Primary Key of any table.

Where could i fileter my results

$
0
0

I was wondering if I could get help on understanding this code and where would i put a where clause  to filter my objects and an OrderBy clause. Thanks !

var purchases = db.Purchases
                    .Select(a => new PurchaseViewModel
                    {
                        PurchaseId = a.PurchaseId,
                        BusinessName = a.BusinessName,
                        Address = a.Address,
                        State= a.State
                    });
            return View(purchases);

Viewing all 1698 articles
Browse latest View live


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