Linq with ef core - entity-framework

how can I use identity tables in asp.net core like AspNetUsers with Linq technique
for example
var x = (from a in db.table1 join b in AspNetUsers .... )

Try to use DbContext.Users to retire user information ,from IdentityDbContext.cs:
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
/// </summary>
public DbSet<TUser> Users { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
/// </summary>
public DbSet<TUserClaim> UserClaims { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
/// </summary>
public DbSet<TUserLogin> UserLogins { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
/// </summary>
public DbSet<TUserRole> UserRoles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
/// </summary>
public DbSet<TUserToken> UserTokens { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
/// </summary>
public DbSet<TRole> Roles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
/// </summary>
public DbSet<TRoleClaim> RoleClaims { get; set; }
Something like :
var categories = from c in db.categories
join u in db.Users
on c.myID equals u.Id
select new { ID=c.myID, name= u.UserName};
var result = categories.ToList();

Related

how to get a list of activities from sendgrid? Do they provide some APIs to get responses based on different categories?

In my project I am working with Sendgrid which is used to send bulk transactional or marketing emails. In my project it is working fine. I am able to send transactional emails from my project. But for reading the activities of each email (like open, click, bounce, invalid-emails), I need to go into my sendgrid account and one by one check, which is very tedius and time consuming option. I want to do it automatically in my project. I have read the sendgrid documentation, but I didn't find any way to get a list of OPEN mails, BOUNCED emails.
could you please help me, how can I do this.
You need to use the WebHooks built into SendGrid. It's called the Event Webhook.
https://sendgrid.com/docs/API_Reference/Webhooks/event.html
Basically you setup the webhook in SendGrid (go to the Settings -> Mail settings) and click on 'Event Notification'. Turn it on and select the events you're interested in. You can use a site called Request bin to test what happens.
http://requestb.in/
I found the easiest way to test this was to fire an email through SendGrid and then see what it sent through requestb.in. I then wrote the API in my system (C# WebApi) based on the data.
I don't know what language / frameworks you're using but here's my API in WebApi/C#.
Api Controller:
[HttpPost]
[Route("api/emailWebHooks")]
public async Task<IHttpActionResult> UpdateEmail(IList<SendGridNotification> sendGridNotifications)
{
Log.Debug("UpdateEmail: " + JsonConvert.SerializeObject(sendGridNotifications));
var updated = await _sendEmailService.UpdateSendGridEmailState(sendGridNotifications);
return Ok(updated);
}
And the class:
public class SendGridNotification
{
/// <summary>
/// The SendGrid event id
/// </summary>
[JsonProperty(PropertyName = "sg_event_id")]
public string SgEventId { get; set; }
/// <summary>
/// The SendGrid message id
/// </summary>
[JsonProperty(PropertyName = "sg_message_id")]
public string SgMessageId { get; set; }
/// <summary>
/// The 'event' property. e.g. Processed
/// </summary>
[JsonProperty(PropertyName = "event")]
public string EventName { get; set; }
/// <summary>
/// The email id - this is unique argument added when the email was sent
/// </summary>
[JsonProperty(PropertyName = "emailId")]
public string EmailId { get; set; }
/// <summary>
/// The email address of the recipient
/// </summary>
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
/// <summary>
/// SendGrid's smtp id
/// </summary>
[JsonProperty(PropertyName = "smtp-id")]
public string SmtpId { get; set; }
/// <summary>
/// The timestamp of the email
/// </summary>
[JsonProperty(PropertyName = "timestamp")]
public long Timestamp { get; set; }
/// <summary>
/// The IP address - of the server?
/// </summary>
[JsonProperty(PropertyName = "ip")]
public string IpAddress { get; set; }
/// <summary>
/// The http response
/// </summary>
[JsonProperty(PropertyName = "response")]
public string Response { get; set; }
}
SendGrid sends a set of responses so make sure you're API handles a list.
The EmailId in the API is a unique argument I sent to SendGrid so that when this message comes back I know which email the message refers to.
Hope this helps

Entity Framework 7.0.0-beta3

The new version of ASPNET Entity Framework 7.0.0-beta3 has changed and I can't find OneToMany.
In the previous version this would work.
#region Table setup
public DbSet<User> Users { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<UserCompany> UserComanies { get; set; }
#endregion
#region Setup DbContext
/// <summary>
/// Build data model in here.
/// </summary>
/// <param name="builder">Builder.</param>
protected override void OnModelCreating(ModelBuilder builder) {
builder.Entity<User>().OneToMany(c => c.UserCompanies, uc => uc.User).ForeignKey(uc => uc.UserId).Required(true);
}
Does anyone know what to do in beta3?
Help would be appreciated.
It is now HasMany, as documented on the Wiki https://github.com/aspnet/EntityFramework/wiki/Using-EF7-in-Traditional-.NET-Applications

ASP.NET MVC 4 Entity Framework entity to get foreign key field from membership user profile table

I have entities in a separate project. One of the entity needs to refer a UserId in UserProfile model in the Web project which is already referencing Entity project. Anybody can help to get a new foreign key to my entity (something like Expense entity class to get additional field Expender which is already a primary key in UserProfile which is a membership table?)
namespace ExpenseAssistant.Entities
{
/// <summary>
/// Expense
/// </summary>
public class ExpenseEntry
{
/// <summary>
/// Gets or sets Unique Id of the Expense
/// </summary>
public virtual int Id { get; set; }
/// <summary>
/// Gets or sets Description about the Expense
/// </summary>
public virtual string ExpenseDescription { get; set; }
/// <summary>
/// Gets or sets the Amount Spent
/// </summary>
public virtual float Amount { get; set; }
/// <summary>
/// Gets or sets the Expender which is the UserId from UserProfile Table
/// </summary>
[ForeignKey("UserProfile")]
public virtual int ExpenderId { get; set; }
}
}
Membership tables are in the same database in which I have all the entity tables.
I tried with update-database in console after adding this key ExpenderId in ExpenseEntry entity, I am getting the error as below,
The ForeignKeyAttribute on property 'ExpenderId' on type
'ExpenseAssistant.Entities.ExpenseEntry' is not valid. The navigation
property 'UserProfile' was not found on the dependent type
'ExpenseAssistant.Entities.ExpenseEntry'. The Name value should be a
valid navigation property name.
Thanks in advance.
There are two problems.
The first problem is that the attribute is meant to be used on a navigation property (which you don't seem to have).
An example of such a navigation property would be:
public virtual UserProfile Expender { get; set; }
The second problem is that the name passed to the ForeignKeyAttribute constructor must be the name of the property containing the foreign key in this class, not the name of the table or entity referenced by the foreign key.
This is what your code should look like:
public virtual int ExpenderId { get; set; }
[ForeignKey("ExpenderId")]
public virtual UserProfile Expender { get; set; }

Entity Framework child objects not populating

I have a simple model which when I run the website in the debugger the entity framework does not correctly populate the model.
The model is simple:
public class Team
{
/// <summary>
/// Constructor required for the EntityFramework to create the object.
/// </summary>
private Team()
{
}
public Team(string name, ApplicationUser owner)
{
Name = name;
Owner = owner;
}
[Required]
public int Id { get; private set; }
[Required]
public string Name { get; private set; }
[Required]
public ApplicationUser Owner { get; private set; }
[Required]
public List<TeamMembership> Members { get; set; }
}
public class TeamMembership
{
/// <summary>
/// Constructor for the EntityFramework
/// </summary>
private TeamMembership()
{
}
public TeamMembership(ApplicationUser user, MembershipStatus status)
{
User = user;
Status = status;
}
[Required]
public ApplicationUser User { get; private set; }
[Required]
public MembershipStatus Status { get; set; }
[Required]
public int Id { get; private set; }
}
Where ApplicationUser is the default class generated by the ASP MVC 5 membership infrastructure.
When I run my tests (Specflow), which create a new LocalDb database with a unique id for each test and runs the migrations on that db, then the entity framework correctly populates my Team and the Owner.
However when I run the website and try and interact with the application then my Team is not fully populated, because the Owner is null and Members is not populated. But the owner ID is set correctly in the database and the query seems ok. The queries executed during the test and the running of the app seem the same.
Why might this be and how might I start to debug the issue?
I feel like I am missing something simple.
You probably need to add .Include() to your query, which isn't shown in your question, but should look something like this:
var query = context.Teams.Include(x => x.Owner).Include(x => x.Members).Where( ... );
EF will only load the top-level entities, but not the entities referenced by it until they're needed (lazy loading). If you haven't disposed of the context, simply attempting to access those navigation properties should cause them to load from the database, but this won't happen if the context has been disposed of.
.Include() will inform EF that those navigation properties need to be eagerly loaded along with the referencing entity.
See this MSDN page for more detail about lazy/eager loading and how to control it.

Why does EF5 code first use datetime2 when inserting a nullable datetime into the database?

I am saving a Cart object to the database that has a nullable datetime. This is the error I get:
The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
There are quite a few stackoverflow posts documenting fixes to this problem. However, when code first is creating the database it will create the field as a DateTime (allow nulls). But for some reason, code first tries to insert using a DateTime2 field.
I am wondering why EF creates the field one way, but inserts using a different type for the same field.
This is the domain object:
using System;
using System.Collections.Generic;
namespace Core.Domain.Cart
{
public partial class Cart : BaseEntity, ILocalizedEntity
{
private ICollection<Catalog> _catalogs;
/// <summary>
/// Gets or sets the name
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// Gets or sets the zone identifier
/// </summary>
public virtual int ZoneId { get; set; }
/// <summary>
/// Gets or sets the brand identifier
/// </summary>
public virtual int BrandId { get; set; }
/// <summary>
/// Gets or sets the customer type identifier
/// </summary>
public virtual int CustomerTypeId { get; set; }
/// <summary>
/// Gets or sets the date and time of the opening of a cart
/// </summary>
public virtual DateTime? OpeningDateUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of the closing of a cart
/// </summary>
public virtual DateTime? ClosingDateUtc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is online or not
/// </summary>
public virtual bool IsOnline { get; set; }
/* Truncated for relevance */
}
}
The model:
using FluentValidation.Attributes;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Telerik.Web.Mvc;
namespace Admin.Models.Cart
{
[Validator(typeof(CartValidator))]
public partial class CartModel : BaseNopEntityModel, ILocalizedModel<CartLocalizedModel>
{
public CartModel()
{
Locales = new List<CartLocalizedModel>();
Catalogs = new List<CatalogModel>();
UnassociatedCatalogs = new List<CatalogModel>();
}
[NopResourceDisplayName("Admin.Carts.Fields.Name")]
[AllowHtml]
public string Name { get; set; }
//Zone dropdown
[NopResourceDisplayName("Admin.Carts.Fields.ZoneList")]
public SelectList ZoneList { get; set; } //The dropdown with zones
public int ZoneId { get; set; } //The selected value of the dropdown once the form is submitted
public string ZoneName { get; set; } //The name of the zone to display in data-grid List view.
//Brand dropdown
[NopResourceDisplayName("Admin.Carts.Fields.BrandList")]
public SelectList BrandList { get; set; } //The dropdown with brands
public int BrandId { get; set; } //The selected value of the dropdown once the form is submitted
public string BrandName { get; set; } //The name of the brand to display in the data-grid List view.
//Customer type dropdown
[NopResourceDisplayName("Admin.Carts.Fields.CustomerTypeList")]
public SelectList CustomerTypeList { get; set; }//The dropdown with CustomerType
public int CustomerTypeId { get; set; } //The selected value of the dropdown once the form is submitted
public string CustomerTypeName { get; set; } //The name of the CustomerType to display in the data-grid List view.
[NopResourceDisplayName("Admin.Carts.Fields.OpeningDateUtc")]
[UIHint("DateNullable")]
public DateTime? OpeningDateUtc { get; set; }
[NopResourceDisplayName("Admin.Carts.Fields.ClosingDateUtc")]
[UIHint("DateNullable")]
public DateTime? ClosingDateUtc { get; set; }
[NopResourceDisplayName("Admin.Carts.Fields.IsOnline")]
public bool IsOnline { get; set; }
/* Truncated for relevance */
}
}
So both the OpeningDateUtc and the ClosingDateUtc are of the type DateTime?.
This is how the database gets generated by EF code first:
The OpeningDateUtc and ClosingDateUtc are created as a nullable DateTime field.
So why is it when I save using the IDBContext.SaveChanges(), the SQL generated for the query is:
exec sp_executesql N'update [dbo].[Cart]
set [Name] = #0, [ZoneId] = #1, [BrandId] = #2, [CustomerTypeId] = #3, [OpeningDateUtc] = #4, [ClosingDateUtc] = #5, [IsOnline] = #6, [IsReadonly] = #7, [IsPreviewMode] = #8, [CreatedOnUtc] = #9
where ([Id] = #10)
',N'#0 nvarchar(100),#1 int,#2 int,#3 int,#4 datetime2(7),#5 datetime2(7),#6 bit,#7 bit,#8 bit,#9 datetime2(7),#10 int',#0=N'Cart1',#1=7,#2=4,#3=5,#4='2013-01-09 00:00:00',#5='2013-01-18 00:00:00',#6=0,#7=0,#8=1,#9='0001-01-01 00:00:00',#10=1
The interesting part being #4 datetime2(7),#5 datetime2(7).
I understand that I could fix this problem by adding a .HasColumnType("datetime2") to the cart map, but it doesn't answer why EF5 (and probably older versions) set them to nullable datetime.
The DateTime type in .NET has the same range and precision as datetime2 in SQL Server. When EF inserts or updates a datetime or datetime2 column in SQL Server it converts the model property to the type that can hold the whole range of DateTime in .NET, that's datetime2. Converting into datetime would fail if the DateTime property is not inside the range of datetime in SQL Server.
The problem that causes the exception are, by the way, not the two nullable OpeningDateUtc and ClosingDateUtc columns, but the CreatedOnUtc value which is '0001-01-01 00:00:00' in your SQL snippet, i.e. CreatedOnUtc is apparently not initialized in your model entity. The earliest date that datetime in SQL Server can store is in the year 1750, so year 0001 won't fit into the type (but it would fit into datetime2).
So, solution is to either set CreatedOnUtc to a valid datetime value or - as you know - define the types as datetime2 in your mapping.
But I agree, there would be less confusion if EF would map DateTime properties by default to datetime2.
The EF Team actually discussed this particular item during one of the design meetings. The decision was to leave the current behavior as is. Here are the meeting notes that can give you more context.