This is my configuration where my primary key column is NetworkId and it's DatabaseGeneratedOption is Identity.
public NetworkConfiguration() : base()
{
this.HasKey(e => e.NetworkId);
Property(e => e.NetworkId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
This value starts from 1 always can I make it to start with 0?
In MVC 3 and EF 4.1 you could try something like this:
context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('NetworkConfiguration', RESEED, 0)");
followed by the method that populates your table with the rest of the values
SeedNetworkConfiguration();
Database ids will always start at 1. Out of interest, why would you want an id to be 0?
Related
i'm going to use dapper as my ORM in asp .net project.
So the problem is, i'm going to execute my procedure to return get data by Id.
If the Id is not exist, the error appeard like this
Sequence contains no elements
is there any solution to prevent the error by using dapper? because the other solution using entity framework.
here's my code
var SP_Name = "SP_GetSupplierById";
parameters.Add("#Id", Id);
var getSupplierById = connection.QuerySingle<Supplier>(SP_Name,parameters,commandType:CommandType.StoredProcedure);
return getSupplierById;
and here's my procedure
CREATE PROCEDURE SP_GetSupplierById
#Id int
AS
SELECT * from TB_M_Supplier where id = #Id;
RETURN 0
Thanks for your help
QuerySingle asserts that there is exactly one row returned; not zero, not multiple. If zero is acceptable, then you can use QuerySingleOrDefault - and check for the default, which will be null in the case of reference types (classes). QuerySingleOrDefault only asserts that there aren't multiple rows; zero is fine.
So
var getSupplierById = connection.QuerySingleOrDefault<Supplier>(SP_Name,parameters,commandType:CommandType.StoredProcedure);
return getSupplierById; // todo: consider null
I have the following functioning LINQ in my .net app
public ActionResult Index()
{
Dictionary<DateTime?, List<Event>> result;
result = (from events in db.Events.Include("Activity")
where events.IsActive
group events by DbFunctions.TruncateTime(events.DateTimeFrom) into dateGroup
select new { EventDate = dateGroup.Key, Events = dateGroup.ToList() }).ToDictionary(x => x.EventDate, x => x.Events);
return View(result);
}
When I use this in EF Core, I can't use DbFunctions. How can I rewrite this to make it work in Microsoft.EntityFrameworkCore ? I am using SQLite if that makes a difference.
In EF6 DbFunctions.TruncateTime is used instead of DateTime.Date property because for some reason the later is not supported.
In EF Core the former is not needed simply because DateTime.Date now is recognized and translated correctly.
group events by events.DateTimeFrom.Date into dateGroup
Unfortunately there is no documentation (yet) of what is supported, so as a general rule of thumb, always try the corresponding CLR method/property (if any) and check if it translates to SQL and how.
To use DbFunctions in ASP.NET CORE You must create an object.
var DbF = Microsoft.EntityFrameworkCore.EF.Functions;
Now you can easily use it.
var now = DateTime.Now;
int count = db.Tbl.Count(w => DbF.DateDiffDay(now, w.RegisterDate) <= 3);
more detail on github
DbFunctions are not supported yet for EF Core. However you can use "Raw Sql Queries".
You can find documentation of "Raw Sql Queries" here
And also you can track here for DbFunctions for EF Core
EF Core 3.0
I finally found an answer that works. The issue is that I was wanting to Group by Date on a DateTime column in the database.
The key for me was to use the EF.Property function. This allows the class to have the DateTime property which is used for adding that level of data, but below allowed me to then redefine it as a Date. However.. I suspect if I decalared the property on the class, it would have already allowed me to use the .Date function which it was not allowing me todo.
So the solution may rather be to define the property on the model, or use the below to define it in your query.
EF.Property(s, "dt").Date
Full code
var myData = _context.ActivityItems
.GroupBy(a => new { nlid = a.lid, nsd = EF.Property<DateTime>(a, "dt").Date })
.Select(g => new
{
g.Key.nlid,
g.Key.nsd,
cnt = g.Count()
});
I managed to rewrite this in Lambda as well and make it async. Seems to be working the same.
var temp = await _context.Events.Where(x => x.IsActive)
.Include(a => a.Activity)
.GroupBy(x => x.DateTimeFrom.Date)
.Select(g => new { EventDate = g.Key, Events = g.ToList() }).ToDictionaryAsync(x => x.EventDate, x => x.Events);
EF Core 2.0 now supports mapping database functions to static methods on your context.
Check out the section 'Database scalar function mapping' here - https://learn.microsoft.com/en-us/ef/core/what-is-new/
In my case, it is working in this way instead of DbFunctions.TruncateTime or EntityFunctions.TruncateTime-
result = _context.ActivityItems.Where(a => a.DateTimeFrom.Value.Date == paramFilter.DateTimeFrom.Value.Date);
It converts date first in the server side in where condition and then compare with parameter date value-
WHERE CONVERT(date, [a].[DateTimeFrom]) = #__paramFilter_DateTimeFrom_Value_Date_0
I recently upgraded my application from ASP.NET MVC 3 and EF 4 to ASP.NET MVC 5 and EF 6. I have several repository functions that I'm using for CRUD functionality.
I haven't changed anything, but I'm suddenly receiving this error if I try to add a record to my entities:
Cannot insert explicit value for identity column in table "Photos" when IDENTITY_INSERT is set to OFF
Here's an example of one of these methods
public void SavePhoto(Photo photo)
{
if (photo.PhotoID == 0) // new photo
_entities.Photos.Add(photo);
else // edit photo
{
_entities.Photos.Attach(photo);
_entities.Entry(photo).State = EntityState.Modified;
}
_entities.SaveChanges();
}
The PhotoID column in my database for this table is set to be the Identity. When this worked before, it would just increment the PhotoID column value based on the last entry (as expected).
Is there a better way to do this now with EF 6?
Is your PhotoId column is "int" type and annotated with "DateGenerated identity"? If so, the following code will error. Because EF might thinking you are inserting 0 into identity column.
if (photo.PhotoID == 0) // new photo
_entities.Photos.Add(photo);
Use id == 0 to check whether it is a new photo or not is not a good practice, actually it is a "bug", because say you have 3 records in the system(which default could mean your photoid is not greater than 4), And somehow you PhotoID was manipulated as 100 in the backend, now when your code run, your code will set its state as Modified. And EF might throw error for you, or EF might try to insert it for you instead of editing.
So I would suggest to use follow code
var photo = _entities.Photos.Find(photo.PhotoId)
if (photo == null) {
//your code to add photo
}
else
{
//your code to set the the modal state to modified.
}
i want to make sure all product names are unique so i tried to do the following.
but it is causing an infinity loop at the lambda expression.
public partial class Product
{
partial void OnProductNameChanging(string value)
{
using(var ctx = new MyEntityContext()){
var val = value;
var item = ctx.Products.Where(o=>o.ProductName == val).FirstOrDefault();
if(item != null)
throw new ValidationException("Product Name existed.");
}
}
}
i'm using asp.net 4.0 with dynamic data and entity framework.
Why don't you set it up on database level and handle exeption in case if product name already exists?
I am not too familiar with EF, but you should get the changeset and compare values. That is, for the Product Entity and in the case of the the changeset having an Update, compare the EXISTING value with NEW, and change the new in the case of duplication.
Here's how to get changeSet in EF :
http://davidhayden.com/blog/dave/archive/2005/11/16/2570.aspx
the comparison and value must be called before any context.SubmitChanges();
Hope this helps.
ok i use this route
routes.MapRoute(
"Catalog/Data",
"Catalog/{*data}",
new { controller = "Catalog", action = "Category", data = "" }
);
the Url looks something like http://localhost/Catalog/Computer/Harddrives/internal
Data beening the Computer/Harddrives/internal part
i split it apart and validate the route
here is where my concerns are, atm i do not check for sql injection
i check the route by getting the category from the database using enitity framework
with this function
public Category GetByRoute(string Route)
{
return (from c in XEntity.CategorySet
.Where(c => c.Route == Route)
.Where(c => c.IsEnabled == true)
select c).FirstOrDefault();
}
should i be worried about sql injection with this?
Linq2Sql and the Entity Framework use SQL parameters (except for one edge case) so you'll be fine.
In your case you're actually using Linq over the CategorySet, and linq is executed locally in this case, so it's CategorySet that's touching the database, the where constraints run after (I believe). Again in this case there's no problem.