.NET MVC视图数据异常求助:移除type字段仅使用firmtypeid
firmtypeid in MVC Hey there! Let's work through your problem step by step—since you're new to MVC, we'll start by tracking down that hidden type=1 filter, then cover how to safely remove the type field and rely solely on firmtypeid.
Step 1: Track Down the type=1 Filter
The unexpected filter is almost certainly hiding in one of these key spots:
1. Your GetTransp... Controller Method
This is the most likely culprit. Dig into the data retrieval logic here—look for explicit LINQ filters like:
var firms = db.Firms.Where(f => f.type == 1).ToList();
Or if it's pulling from a request parameter with a default value that forces type=1:
var selectedType = Request.Query["type"] ?? "1"; var firms = db.Firms.Where(f => f.type == int.Parse(selectedType)).ToList();
Even if no Where clause is visible, check if you're using a stored procedure or database view to fetch data—those might have a WHERE type = 1 condition baked in.
2. The FirmsListViewModel Mapping/Setup
If you're using AutoMapper or manually mapping entities to your view model, check for hidden filters there. For example:
CreateMap<Firm, FirmsListViewModel>() .ForMember(dest => dest.FirmName, opt => opt.MapFrom(src => src.Name)) .BeforeMap((src, dest) => src = src.Where(f => f.type == 1).FirstOrDefault()); // Filter hidden here
Or if the view model's constructor applies a filter when loading data.
3. The Razor View Itself
While less common, check if your view is filtering data inline:
@foreach (var firm in Model.Firms.Where(f => f.type == 1)) { <!-- Render firm details --> }
Or using conditional logic to only render items where type == 1.
4. Database-Level Constraints
Double-check if your SQL table has a default constraint on type set to 1, or if you're querying a database view that includes WHERE type = 1.
Step 2: Migrate to firmtypeid & Remove type
Once you've eliminated the type=1 filter, follow these steps to fully switch to firmtypeid:
- Update your Entity Model: Remove the
typeproperty from yourFirmentity class. - Revise Data Queries: Replace all references to
typein controller logic withfirmtypeid. For example, if you previously filtered bytype, adjust to filter byfirmtypeidinstead. - Update the View: Swap out any instances of
@item.typewith the corresponding value from yourfirmtypeidlookup (e.g., iffirmtypeidlinks to aFirmTypestable, fetch the display name using the ID and render that). - Update the Database: If using Entity Framework, generate a migration to drop the
typecolumn from your SQL table, then run the migration to apply the change. - Test End-to-End: Verify all views and controller actions now use
firmtypeidcorrectly, and that all data is displayed without the oldtype=1restriction.
If you can share the full code of your GetTransp... method and any relevant view/model snippets, I can give even more targeted guidance—but these steps should help you resolve the filter issue and complete the field migration.
内容的提问来源于stack exchange,提问作者SQLfreaq

