![](/img/trans.png)
[英]I can't access the UserName of the logged in user. (ASP.NET Core Web API)
[英]Error getting products from the logged in user. ASP.NET Core MVC
我無法僅獲取登錄用戶(即進行購買的用戶)購買的產品。
我有一個包含一般注冊數據的Users
表和一個Customers
表。
表之間的關系如下:
User
:userId、姓名、email、密碼Customer
:customerId、status、section_id、user_idProduct
:productId、name、price、purchase_date、customer_id 那么, Products
表與Customers
表相關,而不是與Users
表相關。 而且我無法更改它,因為數據庫中還咨詢了其他應用程序。
我嘗試通過這種方式獲取產品,但Customer
的 id 值為 null。
public IActionResult View(int id)
{
User user = _loginUser.GetUser();
Product product = _pedidoRepository.GetProduct(id);
if (product.customer_id != user.Customer.customerId)
{
return new ContentResult() { Content = "Access denied" };
}
return View(product);
}
我得到錯誤:
Project.Models.users.Customer.get 返回 null
如何使Client
ID 可訪問以進行比較?
我的GetUser
方法如下所示:
public user GetUser()
{
// Deserializar
if( _session.Exists(Key))
{
string user JSONString = _session.Consult(Key);
return JsonConvert.DeserializeObject<user>(userJSONString);
}
else
{
return null;
}
}
重要的是,“用戶”和“客戶”之間的關系是一一對應的。 注冊“用戶”時,“客戶”在表中注冊,“用戶”的 fk
Class User.cs
public class User
{
/* PK */
[Key]
public int userId { get; set; }
public string name { get; set; }
public string email{ get; set; }
public string passwor{ get; set; }
[ForeignKey("user_id")]
[JsonIgnore]
public Customer Customer { get; set; }
}
Class Customer.cs
public class Customer
{
/* PK */
[Key]
public int customerId{ get; set; }
public string Status { get; set; }
[Column("user_id")]
[ForeignKey("User")]
public int? user_id { get; set; }
public virtual User User { get; set; }
.
.
}
Class Product.cs
public class Product
{
/* PK */
[Key]
public int productId{ get; set; }
public string name { get; set; }
public decimal price { get; set; }
public DateTime purchase_date { get; set; }
[Column("customer_id")]
[ForeignKey("Customer")]
public int? customer_id{ get; set; }
public virtual Customer Customer { get; set; }
}
我感謝任何評論。 我從語言開始。 如果需要,我可以發送更多代碼。
好吧,我假設您的 session 擁有用戶的 JSON 表示,在某個時候從數據庫中查詢。 發生這種情況時,將在沒有 Customer 導航屬性的情況下查詢用戶(因此它為空)。 當您稍后訪問 User.Customer 時,用戶實體不再附加到 DbContext,因此不會從數據庫加載客戶。 如果我的假設是真的,我會提出兩個選擇:
context.Users.Include(c => c.Customer).GetById(x)
選擇取決於 Cutomer 是與您的大多數呼叫相關還是僅與單個呼叫相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.