小编Sti*_*ian的帖子

EF Core - MERGE 语句与 FOREIGN KEY 约束冲突

我需要一些帮助来理解我尝试更新产品时遇到的错误。

我已经阅读了这个类似的问题,并尝试了接受的答案(_context.SaveChanges()在每个表格之后,在完整产品的最终保存之前),但我仍然遇到如下所述的相同错误。

这些是涉及的模型:

public class Product
{
    public int Id { get; set; }
    // some more properties
    public ICollection<IdentifierForProduct> Identifiers { get; set; }
}

public class IdentifierForProduct
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int ProductIdentifierId { get; set; }
    public string Value { get; set; } // E.g. "4902505154881"

    public ProductIdentifier Identifier { get; set; }
    public Product Product { get; set; }
} …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework-core asp.net-core

8
推荐指数
1
解决办法
8320
查看次数

FK约束可能会导致循环或多级联路径

为什么我最初update-database失败了,我需要在数据库表类中更改什么才能使其工作?

onDelete: ReferentialAction.Cascade当然,我可以将迁移脚本中的更改为onDelete: ReferentialAction.NoAction,但随后我将在应用程序中面临其他问题。我正在寻找一种解决方案,无需编辑add-migration. 换句话说,我愿意更改我的数据库架构。

我想要的行为是,当我删除 a 时Product,关联的ProductPropertyOptionForProducts也会被删除,但反之则不然,而不是ProductPropertyOption与 关联的ProductPropertyOptionForProducts

这是迁移输出错误消息:

在表“PropertyOptionsForProducts”上引入外键约束“FK_PropertyOptionsForProducts_ProductPropertyOptions_ProductPropertyOptionId”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。无法创建约束或索引。请参阅以前的错误。

生成的导致错误的 SQL 命令:

CREATE TABLE[PropertyOptionsForProducts] (
[Id] int NOT NULL IDENTITY,
[CustomNumberValue] decimal (18, 2) NOT NULL,
[CustomRangeFrom] decimal (18, 2) NOT NULL,
[CustomRangeTo] decimal (18, 2) NOT NULL,
[CustomStringValue] nvarchar(max) NULL,
[ProductId] int NOT NULL,
[ProductPropertyId] int NOT NULL,
[ProductPropertyOptionId] int …
Run Code Online (Sandbox Code Playgroud)

c# database-design entity-framework-core ef-core-2.0 entity-framework-migrations

5
推荐指数
2
解决办法
1万
查看次数

如何使用 AutoMapper 映射相关数据

我正在尝试使用 AutoMapper 将三个实体模型映射到一个视图模型中。最终输出应该是一个递归类别树,类别中包含产品。类别树正在工作,但Products视图模型的-property 是null. 我的查询返回类别和产品,所以我认为映射不知道如何将产品映射到视图模型。

我的实体模型:

public class ProductCategory
{
    public int Id { get; set; }
    public int SortOrder { get; set; }
    public string Title { get; set; }
    [ForeignKey(nameof(ParentCategory))]
    public int? ParentId { get; set; }
    // Nav.props:
    public ProductCategory ParentCategory { get; set; }
    public ICollection<ProductCategory> Children { get; set; }
    public List<ProductInCategory> ProductInCategory { get; set; }
}

public class ProductInCategory
{
    public int Id { get; set; }
    public int …
Run Code Online (Sandbox Code Playgroud)

automapper entity-framework-core

3
推荐指数
1
解决办法
1803
查看次数

属性“ a”不是实体类型“ b”的导航属性。为什么不?

我正在尝试通过以下查询加载产品标识符Label的列表(即产品标识符的名称,例如“ EAN”,“产品编号”等)ProductIdentifiers

ICollection<ProductIdentifierInType> typeIds =
            _context.ProductIdentifiersInTypes
            .Include(t => t.Identifier.Label)
            .OrderBy(o => o.SortOrder).ToList();
Run Code Online (Sandbox Code Playgroud)

VS给了我智慧t.Identifier.Label。解决方案编译良好。这是我得到的运行时错误:

InvalidOperationException:属性“ Label”不是实体类型“ ProductIdentifier”的导航属性。“ include(string)”方法只能与“。”一起使用。导航属性名称的分隔列表。

以下是相关的模型类:

public class ProductIdentifierInType
{
    public int Id { get; set; }
    public int ProductTypeId { get; set; }
    public int SortOrder { get; set; }

    public ProductIdentifier Identifier { get; set; }
    public ProductType Type { get; set; }
}

public class ProductIdentifier
{
    public int Id { get; set; }
    public string Label { get; …
Run Code Online (Sandbox Code Playgroud)

linq entity-framework-core ef-core-2.0

3
推荐指数
1
解决办法
2342
查看次数

如何读取 dbo.AspNetUsers 表?

我想从 Identity-table 检索数据dbo.AspNetUsers,但我还没有弄清楚如何查询它。

这是我的数据库上下文:

public class ProjectsDbContext : IdentityDbContext<IdentityUser>
{
    public ProjectsDbContext(DbContextOptions<ProjectsDbContext> options) : base(options) { }

    public DbSet<Project> Projects { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        if (modelBuilder == null)
        {
            throw new NullReferenceException();
        }

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Project>()
            .HasMany(c => c.ChildProjects)
            .WithOne(p => p.ParentProject)
            .HasForeignKey(p => p.ParentProjectId);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的User班级:

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的查询,但不起作用:

List<User> …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework-core asp.net-core-mvc asp.net-core-identity

3
推荐指数
1
解决办法
6031
查看次数

cookie 过期后从 Identity 注销会导致 http 错误 400

在我的_LoginPartial.cshtml我有这个注销按钮:

<form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "", new { area = "" })">
    <button id="logout" type="submit">
        Log out
    </button>
</form>
Run Code Online (Sandbox Code Playgroud)

然后,据我所知,Logout.cshtml.cs被称为:

public class LogoutModel : PageModel
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger<LogoutModel> _logger;

    public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
    {
        _signInManager = signInManager;
        _logger = logger;
    }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPost(string returnUrl = null)
    {
        await _signInManager.SignOutAsync();
        _logger.LogInformation("User logged out.");
        if (returnUrl != null)
        {
            return LocalRedirect(returnUrl);
        }
        else …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core asp.net-core-identity

3
推荐指数
1
解决办法
663
查看次数

从视图组件中获取会话 ID

这段代码可以很好地从控制器中获取会话 ID:

HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
Run Code Online (Sandbox Code Playgroud)

...但是当我尝试将相同的代码放在视图组件类中时,VS 告诉我名称HttpContext.Session.SetString(或只是HttpContext.Session,或只是HttpContext)在当前上下文中不存在。我using Microsoft.AspNetCore.Http;在班上名列前茅。

编辑

这是我的视图组件类:

public class ShoppingCartViewComponent : ViewComponent
{
    private readonly MyStoreContext _context;

    public ShoppingCartViewComponent(MyStoreContext context)
    {
        _context = context;
    }

    // Initialize session to enable SessionId
    // THIS WON'T WORK:
    HttpContext.Session.SetString("_Name", "MyStore");
    string SessionId = HttpContext.Session.Id;

    public async Task<IViewComponentResult> InvokeAsync(int Id)
    {
        var cart = await GetCartAsync(Id);
        return View(cart);
    }

    private async Task<ViewModelShoppingCart> GetCartAsync(int Id)
    {
        var VMCart = await _context.ShoppingCarts …
Run Code Online (Sandbox Code Playgroud)

c# session asp.net-core asp.net-core-viewcomponent

2
推荐指数
1
解决办法
7093
查看次数

如何通过SortOrder对其角色的员工列表进行排序?

我正在尝试对可以具有任意数量的不同角色的员工列表进行排序.角色本身按SortOrder属性排序,我希望员工按照分配给他们的所有角色的最高排序进行排序.

例如:

SortOrder - Role
1 - "Manager"
2 - "Graphics designer"
3 - "Server-tech-guy"
4 - "Web developer"
5 - "Coffee Machine manager"
Run Code Online (Sandbox Code Playgroud)

员工既可以是图形设计师,也可以管理咖啡机.在这种情况下,我只想SortOrder在对员工列表进行排序时使用角色"图形设计器".

这是我的模特:

public class Employee
{
    public int Id { get; set; }
    public int BranchId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public double EmploymentPercentage { …
Run Code Online (Sandbox Code Playgroud)

c# linq entity-framework-core

2
推荐指数
1
解决办法
49
查看次数

如果它存在,.Remove()它,如果没有.Add()它

我有这个动作方法,检查一个项目是否存在,如果存在,它将被删除.如果它不存在,则添加它.这就像是特定项目的开关:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> FrontPageProduct(ViewModelFrontPageProduct frontPageProduct)
{
    var fpp = new FrontPageProduct()
    {
        ProductCategoryId = frontPageProduct.ProductCategoryId,
        ProductId = frontPageProduct.ProductId,
        SortOrder = 0
    };
    bool exists = _context.FrontPageProducts
        .Any(x => x.ProductCategoryId == frontPageProduct.ProductCategoryId 
        && x.ProductId == frontPageProduct.ProductId);
    if (exists)
    {
        var delete = (from d in _context.FrontPageProducts
                         where (d.ProductCategoryId == frontPageProduct.ProductCategoryId && 
                         d.ProductId == frontPageProduct.ProductId)
                         select d).FirstOrDefault();
        _context.Remove(delete);
    }
    else
    {
        _context.Add(fpp);
    }
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index), new { id = fpp.ProductCategoryId, tab = 2 });
}
Run Code Online (Sandbox Code Playgroud)

现在,我觉得这有点长啰嗦.这样做是否有更短但仍然可读的方式?

c# linq entity-framework-core

1
推荐指数
1
解决办法
105
查看次数

为什么我的密码散列函数使用相同的盐生成不同的散列?

存储在我的数据库中的密码是这样加密的:

byte[] salt = NewSalt();
string hashedPassword = HashPassword("passwordInTheClear", salt);
// Add/update the admin-user with hashed password and salt.
Run Code Online (Sandbox Code Playgroud)

散列函数:

public static string HashPassword(string password, byte[] salt)
{
    // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
    return Convert.ToBase64String(KeyDerivation.Pbkdf2(
        password: password,
        salt: salt,
        prf: KeyDerivationPrf.HMACSHA1,
        iterationCount: 10000,
        numBytesRequested: 256 / 8));
}
Run Code Online (Sandbox Code Playgroud)

盐生成器:

public static byte[] NewSalt()
{
    // generate a 128-bit salt using a secure PRNG
    byte[] salt = new byte[128 / 8];
    using (var rng = RandomNumberGenerator.Create()) …
Run Code Online (Sandbox Code Playgroud)

c# encryption password-encryption asp.net-core-mvc

1
推荐指数
1
解决办法
104
查看次数